3 ms·
I was doing this and used it for a year in https://github.com/bbkane/warg/ https://github.com/bbkane/warg/, but ripped it out since Go auto-casts underlying typ
by bbkane 1y ago
I was doing this and used it for a year in https://github.com/bbkane/warg/ https://github.com/bbkane/warg/, but ripped it out since Go auto-casts underlying types to derived types in function calls:
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).
- mattbee 1y agoYep in the same way it would allow `var u userID = 1` it allows `Work(1)` rather than insisting on `var u userID = userID(1)` and `Work(userID(1))`. 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.
- alphazard 1y agoThis is a little misleading. Go will automatically convert a numeric literal (which is a compile time idea not represented at runtime) into the type of the variable it is being assigned to. 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/4eNQOJSmGqD https://go.dev/play/p/4eNQOJSmGqD
- skybrian 1y agoThis only happens for literal values. Mixing up variables of different types will result in a type error. When 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.
- drpixie 1y agoArrggg- that's the best reason, so far, to avoid Go. 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.
- Mawr 1y agoIn order to run into this "issue" you'd have to do exactly what you did here - pass in a literal "1" to a function that expects a userID. That is not an issue of any sort.