We recently reviewed both the standard way to declare variables, and tuple assignments. Let's extend on those concepts and learn how to declare our own types in Go.
Types in Go
A type in Go is a declaration that defines a new named type that we can use in our programs and follows this pattern:
Declaring our types
So let's see how we can use the type keyword to declare our own types based on base data types or from our own structs.
Declaring types based on Structs
A common way to declare our own types is by combining the type and struct keywords. A struct is a custom type that groups different subtypes, known as fields.
For example, if we were developing an application that reads users from a database, we could create the following User type with:
Name string
Email string
}
Then, we could assign values to it using with:
Declaring types based on basic data types
Another way to declare custom types is by declaring them based on basic data types. The advantage is by aligning to the business rules, our code gets more readable. For example:
Comparing Types
However, it's worth noticing one downside of the above declaration. Since two values of different named types cannot be compared directly by the compiler (even if both types are based on the float64 type), we cannot compare them directly:
invalid operation: cm == in (mismatched types int and float64)
The solution would be converting both to the same type and comparing them:
false
Which is not much intuitive, is it?
Conclusion
On this article we learned about declaring named types in Go. Using named types is recommended if it makes the code more readable (for example, to avoid writing out complex types repeatedly). However, consider creating them carefully if your types are based on basic data types since it may decrease readability.
It's also possible to define custom behaviors for our types which we'll see in a future post. Keep tuned!