It hardly needs to be stated that in an assignment, a value must be assignable, but here we are…
Assignment statements
…
In assignments, each value must be assignable to the type of the operand to which it is assigned…
We’ve already talked about assignability, so we won’t go into those details here. But there are some special cases to discuss:
… with the following special cases:
- Any typed value may be assigned to the blank identifier.
Simple enough. You can assign anything to _
, without regard to its type.
_ = int(3)
_, _, err := someFunction()
- If an untyped constant is assigned to a variable of interface type or the blank identifier, the constant is first implicitly converted to its default type.
const max = 3 // max is an untyped numeric constant
var x interface{}
x = max // x's dynamic type is now `int`, the default type for an untyped numeric constant
- If an untyped boolean value is assigned to a variable of interface type or the blank identifier, it is first implicitly converted to type
bool
.
var s string
var x interface{}
x = len(s) == 0 // x's dynamic type is now `bool`
Quotes from The Go Programming Language Specification Language version go1.22 (Feb 6, 2024)