Go Struct

Introduction

A Go struct is a type that contains named fields.

For example, we could represent a circle like this:

type Circle struct { 
    x float64 
    y float64 
    r float64 
} 

The type keyword introduces a new type.

It's followed by the name of the type Circle.

The keyword struct to indicate that we are defining a struct type, and a list of fields inside of curly braces.

We can collapse fields that have the same type:

type Circle struct { 
    x, y, r float64 
} 

Initialization

We can create an instance of our new Circle type in a variety of ways:

var c Circle 

This will create a local Circle variable that is by default set to zero.

For a struct, zero means each of the fields is set to their corresponding zero value.

For example, 0 for ints, 0.0 for floats, "" for strings, nil for pointers, etc.

We can also use the new function:

c  := new(Circle) 

This allocates memory for all the fields, sets each of them to their zero value, and returns a pointer to the struct (*Circle).

Pointers are often used with struct so that functions can modify their contents.

More typically, we want to give each of the fields an initial value.

We can do this in two ways.

The first option looks like this:

c  := Circle{x: 0, y: 0, r: 5} 

The second option is to leave off the field names if we know the order they were defined:

c  := Circle{0, 0, 5} 

This creates the same Circle as the previous example.

If you want a pointer to the struct, use &:

c  := &Circle{0, 0, 5} 



PreviousNext

Related