Function declarations
August 21, 2023
No livestream today. My family is on vacation this week. I’ll be livestreaming again next week!
Function declarations
A function declaration binds an identifier, the function name, to a function.
FunctionDecl = "func" FunctionName [ TypeParameters ] Signature [ FunctionBody ] . FunctionName = identifier . FunctionBody = Block .
Nothing surprising here… So let’s move on to the first interesting rule:
If the function’s signature declares result parameters, the function body’s statement list must end in a terminating statement.
func IndexRune(s string, r rune) int { for i, c := range s { if c == r { return i } } // invalid: missing return statement }
This also makes pretty intuitive sense, but it’s not enforced in all languages, so it’s worth pointing out. Particularly many dynamic languages don’t require an explicit return, and fall back to some sort of default return value when it is omitted. Not true in Go. You must have an explicit return value if the function signature indicates that the function returns something.
But let’s look at one potentially surprising case. The following code is valid, even though the last line is not a return statement. See if you can’t figure out why. (If you can’t, hit reply and let me know… I may do a follow-up post).
func whatType(i any) string {
switch t := i.(type) {
case string:
return "string"
case int, int8, int16, int32, int64, uint, uint8, uint8, uint16, uint32, uint64:
return "integer"
case float32, float64:
return "floating point"
default:
return "unknown"
}
// No return statement... yet this is valid!
}
Quotes from The Go Programming Language Specification Version of August 2, 2023