Usually you define a type like above when you want to make sure that integers (in this case) used for different purposes cannot be mixed up accidentally.
Just adding to the answers here: you might describe a type to give extra meaning to a more primitive type. For example, in the stdlib byte is just an alias for uint8 - but byte holds a different meaning to developers. Here’s a real-world scenario I deal with all the time, where I might have different cloud providers. Declare a type for my providers (or whatever):
… which makes the intended use in this function much more obvious:
func doSomething(provider BlockStorageProvider) {
// In reality this might return a client or do something
switch provider {
case AWS:
fmt.Println("Doing something with AWS")
case GoogleCloud:
fmt.Println("Doing something with Google Cloud")
case Azure:
fmt.Println("Doing something with Azure")
default:
fmt.Println("Unknown provider:", provider)
}
}
I COULD just pass in a uint8 there with a note to look in the constants for the options, but by declaring a type I’m giving uint8 extra meaning. Just like byte means something different in my mind than uint8 even though they’re the same thing. Take a look at the go source for more examples of this: