Quidest?

Struct in Go

ยท Lorenzo Drumond

A struct in Go is a structured data type: something that contains multiple different bits of information, united into a single record.

A struct is a colection of fields.

 1package main
 2
 3import "fmt"
 4
 5type Vertex struct {
 6	X int
 7	Y int
 8}
 9
10func main() {
11	fmt.Println(Vertex{1, 2})
12}

Struct fields are accessed using a dot.

 1package main
 2
 3import "fmt"
 4
 5type Vertex struct {
 6	X int
 7	Y int
 8}
 9
10func main() {
11	v := Vertex{1, 2}
12	v.X = 4
13	fmt.Println(v.X)
14}

A struct literal denotes a newly allocated struct value by listing the values of its fields.

You can list just a subset of fields by using the Name: syntax. (And the order of named fields is irrelevant.)

The special prefix & returns a pointer to the struct value.

E.g.:

 1package main
 2
 3import "fmt"
 4
 5type Vertex struct {
 6	X, Y int
 7}
 8
 9var (
10	v1 = Vertex{1, 2}  // has type Vertex
11	v2 = Vertex{X: 1}  // Y:0 is implicit
12	v3 = Vertex{}      // X:0 and Y:0
13	p  = &Vertex{1, 2} // has type *Vertex
14)
15
16func main() {
17	fmt.Println(v1, p, v2, v3)
18}

References

Next -> go-slices

Next -> go-arrays

#structured #data #go #type