Variables and struct fields

February 7, 2023

Variables

Structured variables of array, slice, and struct types have elements and fields that may be addressed individually. Each such element acts like a variable.

This is pretty straight forward. In most contexts, the elements of a struct, array, or slice, can be treated as variables. They can be assigned, or assigned to, using the same syntax.

A few examples to illustrate:

type Person struct {
	ID   int
	Name string
	Age  *int
}

var p Person // p is an instance of the Person struct, with each field initially
             // set to its zero value.

p.ID = 123 // Assign value to p.ID

fmt.Println(p.Name) // Print the zero value (the empty string) of p.Name

fmt.Println(p.Age) // Panic. Because p.Age is a pointer to int, and not
                   // initalized, as with new(), dereferencing it is not allowed.

var age = int(43)

p.Age = &age // Now p.Age properly points to an int, which contains the value 43

Quotes from The Go Programming Language Specification, Version of January 19, 2023


Share this

Direct to your inbox, daily. I respect your privacy .

Unsure? Browse the archive .

Related Content


Struct tags

Struct types … A field declaration may be followed by an optional string literal tag, which becomes an attribute for all the fields in the corresponding field declaration. An empty tag string is equivalent to an absent tag. The tags are made visible through a reflection interface and take part in type identity for structs but are otherwise ignored. struct { x, y float64 "" // an empty tag string is like an absent tag name string "any string is permitted as a tag" _ [4]byte "ceci n'est pas un champ de structure" } // A struct corresponding to a TimeStamp protocol buffer.


Struct field promotion

Yesterday we learned that structs can have embedded fields. Although we didn’t really learn about any of the special powers this gives us. Today we’ll have a look at those powers. One advantage to using an embedded type is that the implicit field name (the one derrived from the type, Person, in our example) can be omitted. This is the result of “promotion”. For example: var e Employee e.Name = "Bob" // equivalent to e.


Embedded struct fields

When I introduced structs last week, I skipped over one sentence. Today I’m going to address that. Struct types A struct is a sequence of named elements, called fields, each of which has a name and a type. Field names may be specified explicitly (IdentifierList) or implicitly (EmbeddedField). Within a struct, non-blank field names must be unique. We already saw how field names are expressed explicitly. But what is an embedded field?