Skip to content

Ternary operator #19

Open
Open
@joonas-fi

Description

@joonas-fi

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)
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions