匿名函数
1
2
3
4
5
6
7
8
9
10
11
12
13
14package main
import "fmt"
func main(){
a:=1
b:=2
f := func(a int, b int) int {
fmt.Println(a,b)
return a
}
c := f(a,b)
fmt.Println(c)
}闭包
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17package main
import "fmt"
func test1() func()int{
var a int
return func() int {
a ++
return a
}
}
func main(){
f := test1()
for i:=0;i<10;i++ {
fmt.Println(f())
}
}递归
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16package main
import "fmt"
func main(){
test1(10)
}
func test1(a int){
if a <=0{
return
}
a--
fmt.Println(a)
test1(a)
}随机种子
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16package main
import (
"fmt"
"math/rand"
"time"
)
func main(){
rand.Seed(time.Now().UnixNano())
for i := 0; i<10; i ++{
x:= rand.Intn(100)
fmt.Println(x)
}
}map
1
2
3
4
5
6
7
8
9
10
11
12
13package main
import "fmt"
func main(){
a := make(map[int]string)
a[1] = "张三"
fmt.Println(a)
for k,v:= range a{
fmt.Println(k,v)
}
delete(a,1)
}切片
1
2
3
4
5
6
7
8
9package main
import "fmt"
func main(){
a := make([]int, 5,6)
a = append(a, 1,2,3,4,5,5,5,5)
fmt.Println(a)
}结构体
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18package main
import (
"fmt"
)
type Student struct{
id int
name string
}
func main(){
var s Student
s.id = 101
s.name = "sss"
fmt.Print(s)
S := Student{id:103,name:"ccc"}
fmt.Println(S)
}指针
1
2
3
4
5
6
7
8
9
10
11package main
import "fmt"
func main(){
var p *int // 默认值 nil,但是不会分配地址,为空指针
fmt.Println(p)
p = new(int) //默认在堆区分配一个地址, 值为数据类型的默认值
fmt.Println(p)
fmt.Println(*p)
}make 和new的区别,new返回的永远是一个指针,make返回的是对应的数据类型