Chapter 12. Structs Recipes

12.0 Introduction

In Go, a struct is a collection of named data fields. It is used to group related data to represent an entity. Structs are usually defined and later instantiated when needed.

Structs are an important construct in Go. For programmers who come from an object-oriented programming background, this will be familiar (and maybe unfamiliar at the same time) as structs can be considered a stand-in for classes. Some concepts are similar; for example, you can define a struct like you define a class, and you can define methods for a struct as well. Go also supports polymorphism using interfaces and encapsulation using exported and nonexported struct fields and methods.

However, structs do not inherit from other structs (you can compose structs with other structs, though), and there are no objects (though instances of structs are sometimes called objects) because there are no classes.

Go is a profoundly object oriented language.

Rob Pike

Go is object oriented, but it’s not type oriented.

Russ Cox

12.1 Defining Structs

Problem

You want to define a struct.

Solution

Define a struct using the type …​ struct syntax.

Discussion

To define a struct you can use the type …​ struct syntax. Start with a struct that represents data related to a person:

type Person struct {
	Id     int
	Name   string
	Email  string
}

You can group all kinds of data types within a struct, even other structs. For example, if you want to add a date of birth to the Person

Get Go Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.