Skip to content

proposal: math: add Bool(bool) int #61915

@jimmyfrasche

Description

@jimmyfrasche

Helper to convert boolean expressions to numeric types under the standard false = 0, true = 1 mapping.

package math
func Bool[T number](v bool) T {
  if v {
    return 1
  }
  return 0
}

where number is replaced by the constraint for all numeric types, wherever that ends up and whatever it ends up being named.

As inference improves, the type should need to be specified less often.

I don't think the name is too important at this point. The important parts are is this the right thing in the right place. Names can be discussed once those are decided.

A language change to allow direct conversion from a boolean expression to a numeric type has been rejected several times, #9367 and #45320 . This is the next best thing.

This has been forked from discussion in #61643.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions