LESSON · 1 OF 33

Defining a struct type

Defining a struct type

A struct groups related fields into one named type. Where a slice holds many of the same thing and a map holds key-value pairs, a struct holds a fixed set of named fields that belong together - a server's name, IP, and port, say. It is how you model a "thing" in Go.

You define one with type, a name, the keyword struct, and a block of fields, each written as name type:

go
type Server struct {
    Name string
    IP   string
    Port int
}

Now Server is a type you can use like any other: declare variables of it, pass it to functions, return it, put it in a slice.

Without a struct you would pass a server's name, IP, and port around as three separate variables and hope they stay in sync. A struct keeps them together as one value, so a function takes one Server instead of three loose arguments. This is the backbone of modelling real things - a config, a request, a check result - as data.

The shape to memorise: type Name struct { field type }.

Spin up a fresh environment and practice live.
go · fresh machine · ready in under a minute