No livestream today. I wasn’t feeling well enough. No live stream next week either, as I’ll be traveling.
Expression statements
With the exception of specific built-in functions, function and method calls and receive operations can appear in statement context. Such statements may be parenthesized.
ExpressionStmt = Expression .
The following built-in functions are not permitted in statement context:
append cap complex imag len make new real unsafe.Add unsafe.Alignof unsafe.Offsetof unsafe.Sizeof unsafe.Slice unsafe.SliceData unsafe.String unsafe.StringData
Okay. That sounds like it should be obvious. But it also sounds confusing. At leat it was to me at first.
What exactly is “statement context”, and why are some built-in functions not permitted in it?
Think of it this way: A statement expresses a “complete thought” (completely my term—not one taken from the spec).
Function and method calls can express a “complete thought”—by discarding the return value. But this list of built-in functions is an exception, in that they must be part of a larger expression.
The spec goes on to provide a few examples:
h(x+y) f.Close() <-ch (<-ch) len("foo") // illegal if len is the built-in function
Let’s expand on that last one, as a point of example.
What happens if you try to call the built-in len
function this way?
We get a build failure and an error:
len("foo") (constant 3 of type int) is not used
But if we assign the value to something—even just the blank identifier, then we have a complete expression statement, which can stand alone as a statement:
_ = len("foo")
Quotes from The Go Programming Language Specification Language version go1.22 (Feb 6, 2024)