Structs

Creating

// Since it is not Uppercase, it is only available inside the package
type user struct {
    name string
    email string
}

Nesting structs

type system struct {
    date string
    user user
}

Struct tags

You can assign metadata to struct fields.

Some Go package functions make use of them.

For instance, the json Go package uses metadata to define the key property names. Without the metadata the json keys would be Date: "", User: "", and with them date: "", user_data: "".

type system struct {
    Date string `json:"date"`
    User user `json:"user_data"`
}

Assiging values

Struct Literal or Composite Literal

Or you assign pass variable values.

If the values are passed in the same order as they were declared in the structure you may omit the keys. (Otherwise values will be assigned to the wrong keys)

Access property values

Use . to access a struct property value.

Structs as parameters

Struct Methods

You can attach functions as struct properties, to give behavior to structures variables.

The function is not declared inside the structure, like it is in a JS class.

Instead it is normally declared in the .go file, along with the structure, but you provide a special parameter called Receiver which states that the function belongs to the structure and allows the function to access the structure properties.

Mutating struct values

To mutate and change the data you have to pass the Receiver as a pointer.

Just like regular function parameters, the Receiver parameter is also by default passed by value.

constructors

These are convention functions to handle the creation of "new instances" of struct variables.

They are not Go features, but only a convention pattern.

Isolating them in packages

Following object oriented principles

The constructor should be available, or even other types of design patterns, to preserve entity integrity.

This way you may even set validation on struct creation.

Struct embedding

Also known as inheritance in other Object Oriented languages.

Define anonymously

Define with a specific name

Last updated