type Celsius int
that in theory prevent you from passing a bare int and mixing up Celsius/Fahrenheit.In go this almost works. If you define
type Celsius int
func isBoiling(t Celsius) bool {
return t >= 100
}
then You need to call it by doing something like t := Celsius(100)
isBoiling(t)
and just t := 212
isBoiling(t)
will not compile with cannot use t (type int) as type Celsius in argument to isBoiling
But unfortunately you can get away with isBoiling(212)
However, If you just used a type alias then you'd be able to do either.This would define a new, non-interchangeable type, even though it's just an int behind the scenes. The new type alias on the other hand define a new name for an existing type; you still have just one type. In the user ID example above that's not what you want, it would allow using an int where a UserID is required.
It is not due to some unkind turn of fortune that the Go type system drops the ball here and there.
> However, If you just used a type alias then you'd be able to do either.
The important distinction between a type and an alias is that you can define methods for a type and you can not do the same for an alias.
I don't know that I would build the same kind of type machinery though (I might only use the alias, not the actual type), since a call like
isBoiling(212)
would fall apart.In particular, I think the type aliasing will make function signatures a lot clearer -- if I to write a `Celsius` type class, I would likely just make a small, hopefully simple `Temperature` type. Unfortunately last time I wrote any Go code, I wasn't anywhere near that careful/purposeful with the types (I mostly left things as `int`s, etc)
You can't get away with:
isBoiling(Fahrenheight(212))
cannot use 212 (type Fahrenheight) as type Celsius in argument to isBoiling func Fahrenheight(f int) Celsius {
return Celsius(5*(f-32)/9)
} type (
Celsius float64
Fahrenheit float64
)This then avoids the patch of 40k lines changed as you can gradually go to different teams and get a checkmark that the changes you made to the teams code is still going to work as expected. This is usually better coordination-wise than a 40k line patch everyone has to sign off on.