1. The main and init Functions
A package can contain multiple init functions, but it must contain exactly one main function.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
| package main
import (
"fmt"
)
func init() {
fmt.Println("init 1")
}
func init() {
fmt.Println("init 2")
}
func main() {
fmt.Println("main")
}
// init 1
// init 2
// main
|
2. The defer Function
Go does not execute code decorated with defer immediately; it marks it and runs it before the program exits.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| package main
import (
"fmt"
)
func main() {
defer func() {
fmt.Println("before exit, in defer")
}()
fmt.Println("I am in main")
}
// I am in main
// before exit, in defer
|
3. The panic and recover Functions
Exception handling in Go: throw a panic, then use recover inside a defer to catch the exception and rethrow the panic to the layer above.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
| package main
import (
"fmt"
)
func main() {
defer fmt.Println("I am in main")
defer func() {
if err := recover(); err != nil {
fmt.Println(err)
// do something
}
}()
panic("error message")
}
// error message
// I am in main
|
4. The new and make Functions
Prototype:
Example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| package main
import (
"fmt"
)
func main() {
tmp := new(int)
fmt.Printf("tmp --> %#v \n", tmp)
fmt.Printf("tmp point to --> %#v \n ", *tmp)
}
// tmp --> (*int)(0x40e020)
// tmp point to --> 0
|
new is used to allocate memory; its argument is a type, and it returns a pointer to the allocated zero value.
Prototype:
1
| func make(Type, size IntegerType) Type
|
Example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
| package main
import (
"fmt"
)
func main() {
var s1 []int
fmt.Printf("s1 is --> %#v \n", s1)
s2 := make([]int, 3)
fmt.Printf("s2 is --> %#v \n", s2)
}
// s1 is --> []int(nil)
// s2 is --> []int{0, 0, 0}
|
make is used to allocate memory and initialize an object for the slice, map, or chan type; its argument is a type. But make returns a reference to the type rather than a pointer.
Difference: new only zeroes the memory, whereas make initializes the data referenced by a slice, map, or chan.