Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ternary operator #19

Open
joonas-fi opened this issue Mar 6, 2023 · 0 comments
Open

Ternary operator #19

joonas-fi opened this issue Mar 6, 2023 · 0 comments
Labels
enhancement New feature or request

Comments

@joonas-fi
Copy link
Member

Prototype:

// 'ternary operator'
func IfElseAssign[T any](val bool, ifTrue T, ifFalse T) T {
	if val {
		return ifTrue
	} else {
		return ifFalse
	}
}

// 'ternary operator' (lazy production of value)
func IfElseAssignFn[T any](val bool, ifTrue func() T, ifFalse func() T) T {
	if val {
		return ifTrue()
	} else {
		return ifFalse()
	}
}

// "adapter" for making values for `IfElseAssignFn` without having to type the full `func () string { return "foo" }`
func fn[T any](val T) func() T {
	return func() T { return val }
}

func main() {
	name := "Joonas"
	powerEstimate := IfElseAssignFn(name == "Joonas", fn(9001), fn(3))
	powerEstimate = IfElseAssign(name == "Joonas", 9001, 3)
	fmt.Printf("Power of %s = %d\n", name, powerEstimate)
}
@joonas-fi joonas-fi added the enhancement New feature or request label Mar 6, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

1 participant