Skip to content

proposal: support int(bool) conversions in Go.1.5 (language change) #9367

Closed
@alandonovan

Description

@alandonovan

I propose the following language change for Go 1.5:

An explicit conversion int(b) where b has a boolean type would become legal, and would yield 1 if b is true, 0 otherwise.  Similar conversions would be legal for all numeric types.

Rationale: currently this function cannot be computed in a single expression, despite it being often useful, hard to misuse, efficiently implemented by modern ALUs, present in nearly all other languages, and syntactically natural in Go.

While I appreciate the value of avoiding implicit int/bool conversions, forbidding explicit ones seems slightly obtuse, and as a result of its omission, one must write four extra lines of code:

 var i int
 if b { 
     i = 1
 }
 ... i ...

which the gc compiler does not optimize this into the obvious single instruction.

The reverse operation bool(i), is not essential since i != 0 has the same effect and can be used in an expression context, but could be added for symmetry.  (I have no strong opinion.)

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions