mirror of https://github.com/tailscale/tailscale/
types/bools: add IfElse (#14272)
The IfElse function is equivalent to the ternary (c ? a : b) operator in many other languages like C. Unfortunately, this function cannot perform short-circuit evaluation like in many other languages, but this is a restriction that's not much different than the pre-existing cmp.Or function. The argument against ternary operators in Go is that nested ternary operators become unreadable (e.g., (c1 ? (c2 ? a : b) : (c2 ? x : y))). But a single layer of ternary expressions can sometimes make code much more readable. Having the bools.IfElse function gives code authors the ability to decide whether use of this is more readable or not. Obviously, code authors will need to be judicious about their use of this helper function. Readability is more of an art than a science. Updates #cleanup Signed-off-by: Joe Tsai <joetsai@digital-static.net>pull/14368/head
parent
0045860060
commit
c9188d7760
@ -0,0 +1,28 @@
|
||||
// Copyright (c) Tailscale Inc & AUTHORS
|
||||
// SPDX-License-Identifier: BSD-3-Clause
|
||||
|
||||
// Package bools contains the [Compare] and [Select] functions.
|
||||
package bools
|
||||
|
||||
// Compare compares two boolean values as if false is ordered before true.
|
||||
func Compare[T ~bool](x, y T) int {
|
||||
switch {
|
||||
case x == false && y == true:
|
||||
return -1
|
||||
case x == true && y == false:
|
||||
return +1
|
||||
default:
|
||||
return 0
|
||||
}
|
||||
}
|
||||
|
||||
// IfElse is a ternary operator that returns trueVal if condExpr is true
|
||||
// otherwise it returns falseVal.
|
||||
// IfElse(c, a, b) is roughly equivalent to (c ? a : b) in languages like C.
|
||||
func IfElse[T any](condExpr bool, trueVal T, falseVal T) T {
|
||||
if condExpr {
|
||||
return trueVal
|
||||
} else {
|
||||
return falseVal
|
||||
}
|
||||
}
|
||||
@ -1,17 +0,0 @@
|
||||
// Copyright (c) Tailscale Inc & AUTHORS
|
||||
// SPDX-License-Identifier: BSD-3-Clause
|
||||
|
||||
// Package bools contains the bools.Compare function.
|
||||
package bools
|
||||
|
||||
// Compare compares two boolean values as if false is ordered before true.
|
||||
func Compare[T ~bool](x, y T) int {
|
||||
switch {
|
||||
case x == false && y == true:
|
||||
return -1
|
||||
case x == true && y == false:
|
||||
return +1
|
||||
default:
|
||||
return 0
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue