Tuesday, January 12, 2021

Declaring Types in Go

Learn how to declare your own types in Go.

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:

type name underlying-type

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:

type User struct {
Name  string
Email string

Then, we could assign values to it using with:

u1 := User{"John", "john@mail.com"}

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: 

type Inch float64
type Centimeter float64

func main() {
var in Inch
var cm Centimeter
in = 10
cm = 25.4
fmt.Println(in, cm)

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:

cm == in
invalid operation: cm == in (mismatched types int and float64)

The solution would be converting both to the same type and comparing them:

fmt.Println(in == Inch(cm))

Which is not much intuitive, is it?


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!

See Also

Any comment about this page? Please contact us on Twitter

Featured Article

Pointers in Go

Understand all about declaring and using pointers in Go If you're coming from Python, Java, JavaScript, C# and others, tal...

Popular Posts