Skip to content

Structs in Go

A struct is a type that contains one or more variables. Itโ€™s like a collection of variables. We call them fields. And they can have differnet types.

Hereโ€™s an example of a struct definition:

type Person struct {
	Name string
	Age int
}

Note that I used uppercase names for the fields, otherwise those will be private to the package and when you pass the struct to a function provided by another package, like the ones we use to work with JSON or database, those fields cannot be accessed.

Once we define a struct we can initialize a variable with that type:

flavio := Person{"Flavio", 39}

and we can access the individual fields using the dot syntax:

flavio.Age //39
flavio.Name //"Flavio"

You can also initialize a new variable from a struct in this way:

flavio := Person{Age: 39, Name: "Flavio"}

This lets you initialize only one field too:

flavio := Person{Age: 39}

or even initialize it without any value:

flavio := Person{}

//or

var flavio Person

and set the values later:

flavio.Name = "Flavio"
flavio.Age = 39

Structs are useful because you can group unrelated data and pass it around to/from functions, store in a slice, and more.

Once defined, a struct is a type like int or string and this means you can use it inside other structs too:

type FullName struct {
	FirstName string
	LastName string
}

type Person struct {
	Name FullName
	Age int
}
โ†’ Download my free Go Handbook!

THE VALLEY OF CODE

THE WEB DEVELOPER's MANUAL

You might be interested in those things I do:

  • Learn to code in THE VALLEY OF CODE, your your web development manual
  • Find a ton of Web Development projects to learn modern tech stacks in practice in THE VALLEY OF CODE PRO
  • I wrote 16 books for beginner software developers, DOWNLOAD THEM NOW
  • Every year I organize a hands-on cohort course coding BOOTCAMP to teach you how to build a complex, modern Web Application in practice (next edition February-March-April-May 2024)
  • Learn how to start a solopreneur business on the Internet with SOLO LAB (next edition in 2024)
  • Find me on X

Related posts that talk about go: