- Pointers
- *T is type: a pointer to T.
var x *int - Operator & generate a pointer to its operand
i :=42
p =&i - The * operator denote the pointer's underlying value.
i = 43
fmt. Println(i)
- *T is type: a pointer to T.
- Struct
type Vertex struct{
X int
Y int
}
- Fields are accessed using dot.
- Struct fields can be accessed through pointers and dot.
v := Vertext {1,2}
p = &v
p.X = 10 - Struct literals denote the fields of the struct by listing. You can specify only part of them using
Name:
syntax.
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
- Array
The type[n]T
is an array ofn
values of typeT
The size of an array is part of its type. So it cannot be resized *
-
Slice: a slice points to an array of values and also include a length.
[]T
is a slice of typeT
len(s)
return the length of slices
.Slice can be nested( slice of slices).
Slicing slices: Slices can be re-sliced, creating a new slice value that points to the same array.
s[lo:hi]
evaluate slice fromlo
tohi-1
inclusively.Make slices:
a := make([]int, 5) // len(a)=5
b := make([]int, 0, 5) // len(b)=0, cap(b)=5Zero of slice is
nil
Adding elements to slice.
func append(s []T, vs ...T) []T-
Range is a form of for loop. Two values are used. The first one is the index and the second is the value in the array.
var pow = []int{1, 2, 4, 8, 16, 32, 64, 128} func main() { for i, v := range pow { fmt.Printf("2**%d = %d\n", i, v) } }
You can skip the index or value by assigning to _.
pow := make([]int, 10)
for i := range pow {
pow[i] = 1 << uint(i)
}
for _, value := range pow {
fmt.Printf("%d\n", value)
}
- Map
- Map must be created with
make
before used -
var m = map[sting] Vertex
key is of type string and value is of type Vertex. - Mutating maps:
- Insert
m[key]=elem - Retrieve
elem= m[key] - Delete
delete (m , key) - Test existence
elem, ok = m[key]
if thekey
is inm
,ok
istrue
. IFkey
is not inm
,elem
is the zero value of that type.
- Insert
- Function values
Go functions may be closures. A closure is a function value that references variables from outside its body. The function may access and assign to the referenced variables; in this sense the function is "bound" to the variables.
func adder() func(int) int {
sum := 0
return func(x int) int {
sum += x
return sum
}
}
func main() {
pos, neg := adder(), adder()
for i := 0; i < 10; i++ {
fmt.Println(
pos(i),
neg(-2*i),
)
}
}