A Tour of Go - Basics: More types: structs, slices, and maps. Flashcards
Does Go have pointers?
Go has pointers. A pointer holds the memory address of a value.
The type *T
is a pointer to a T
value. Its zero value is nil.
var p *int
What is the address operator?
The & generates a pointer to it’s operand
i := 42 p := &i
What is the derefence operator?
The * operator denotes the pointer’s underlying value.
fmt.Println(*p) *p = 21
Does Go support pointer arithmetic like ‘C’?
No.
How is a struct declared in Go?
A struct is a collection of fields
type Vertex struct { X int Y int }
How are struct fields accessed?
Using a dot
var v Vertex v.X = 1 x.Y = 5
How are fields accessed with a struct pointer?
To access the field X of a struct when we have the struct pointer p we could write (*p).X. However, that notation is cumbersome, so the language permits us instead to write just p.X, without the explicit dereference.
v := &Vertex{} (*v).X = 1 v.Y = 5
What are struct literals?
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.
v1 = Vertex{1, 2} // has type Vertex v2 = Vertex{X: 1} // Y:0 is implicit v3 = Vertex{} // X:0 and Y:0 p = &Vertex{1, 2} // has type *Vertex
How are arrays declared?
The type [n]T is an array of n values of type T.
var a [10]int
An array’s length is ….
An array’s length is part of its type, so arrays cannot be resized.
What is a slice?
An array has a fixed size. A slice, on the other hand, is a dynamically-sized, flexible view into the elements of an array.
How is a slice declared?
The type []T
is a slice with elements of type T
.
primes := [6]int{2, 3, 5, 7, 11, 13} var s []int = primes[1:4]
What is a slice literal?
A slice literal is like an array literal without the length.
r := []bool{true, false, true}
This creates an array then builds a slice that references it.
What are the defaults for a slice lower bound?
zero
What is the default for a slice upper bound?
The length of the array - len(s)