by bbkane · 1y ago · 0 comments
Type userID int64
func Work(u userID) {...}
Work(1) // Go accepts this
I think I recalled that correctly. Since things like that were most of what I was doing I didn't feel the safety benefit in many places, but had to remember to cast the type in others (iirc, saving to a struct field manually).Go will not automatically cast a variable of one type to another. That still has to be done explicitly.
func main() {
var x int64 = 1
Func(SpecialInt64(x)) // this will work
Func(x) // this will not work
}
type SpecialInt64 int64
func Func(x SpecialInt64) {
}
https://go.dev/play/p/4eNQOJSmGqDWhen you write 42 in Go, it’s not an int32 or int64 or some more specific type. It’s automatically inferred to have the correct type. This applies even for user-defined numeric types.
Almost nothing is a number. A length is not a number, an age is not a number, a phone number is not a number - sin(2inches) is meaningless, 30years^2 is meaningless, phone#*2 is meaningless, and 2inches+30years is certainly meaningless - but most of our languages permit us to construct, and use, and confuse these meaningless things.
I teach Go a few times a year, and this comes up a few times a year. I've not got a good answer why this is consistent with such an otherwise-explicit language.