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)
}
In go this almost works. If you define
then You need to call it by doing something like and just will not compile with But unfortunately you can get away with However, If you just used a type alias then you'd be able to do either.