[Go] structs, slices, and maps その1

### 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

func main(){
	i, j := 42, 2701

	p := &i
	fmt.Println(*p)
	*p = 21
	fmt.Println(i)

	p = &j
	*p = *p / 37
	fmt.Println(j)
}

$ go build hello.go && ./hello
42
21
73

### Structs
A struct is a collection of fields.

type Vertex struct {
	X int
	Y int
}

func main(){
	fmt.Println(Vertex{1, 2})
}

Struct fields are accessed using a dot.

type Vertex struct {
	X int
	Y int
}

func main(){
	v := Vertex{1, 2}
	v.X = 4
	fmt.Println(v.X)
}

Pointers to structs

type Vertex struct {
	X int
	Y int
}

func main(){
	v := Vertex{1, 2}
	p := &v
	p.X = 1e9
	fmt.Println(v)
}

$ go build hello.go && ./hello
{1000000000 2}

– Struct Literals
A struct literal donates a newly allocated struct value by listing the values of its fields.

var (
	v1 = Vertex{1, 2}
	v2 = Vertex{X: 1}
	v3 = Vertex{}
	p = &Vertex{1, 2}
)

func main(){
	fmt.Println(v1, p, v2, v3)
}

$ go build hello.go && ./hello
{1 2} &{1 2} {1 0} {0 0}

### Arrays
The type [n]T is an array of n values of type T.

func main(){
	var a [2]string
	a[0] = "Hello"
	a[1] = "world"
	fmt.Println(a[0], a[1])
	fmt.Println(a)

	primes := [6]int{2, 3, 5, 7, 11, 13}
	fmt.Println(primes)
}

$ go build hello.go && ./hello
Hello world
[Hello world]
[2 3 5 7 11 13]

– Slices
An array has a fixed size. A slice, on the other hand, is a dynamically-sized, flexible view into the elements of an array.

func main(){
	primes := [6]int{2, 3, 5, 7, 11, 13}

	var s []int = primes[1:4]
	fmt.Println(s)
}

– Slices are like references to arrays
A slice does not store any data, it just describes a section of an underlying array.

func main(){
	names := [4]string{
		"John",
		"Paul",
		"George",
		"Ringo",
	}
	fmt.Println(names)

	a := names[0:2]
	b := names[1:3]

	b[0] = "XXX"
	fmt.Println(a, b)
	fmt.Println(names)
}

$ go build hello.go && ./hello
[John Paul George Ringo]
[John XXX] [XXX George]
[John XXX George Ringo]

– Slice literals
A slice literal is like an array literal without the length.

func main(){
	q := []int{2, 3, 5, 7, 11, 13}
	fmt.Println(q)

	r := []bool{true, false, true, true, false, true}
	fmt.Println(r)

	s := []struct {
		i int
		b bool
	}{
		{2, true},
		{3, false},
		{5, true},
		{7, true},
		{11, false},
		{13, true},
	}
	fmt.Println(s)
}

C言語をやってからポインターは暫く離れていたが、Goもポインター使うのか。