1 func pointer_test() { 2 //空指针,输出为nil 3 var p *int 4 fmt.Printf("p: %v\n", p) 5 //指向局部变量,变量值初始为0 6 var i int 7 p = &i 8 fmt.Printf("p: %v,%v\n", p, *p) 9 //通过指针修改变量数值 10 *p = 8 11 fmt.Printf("p: %v,%v\n", p, *p) 12 //数组的初始化及输出 13 m := [3]int{3, 4, 5} 14 fmt.Printf("m:%v--%v,%v,%v\n", m, m[0], m[1], m[2]) 15 //指针数组的初始化及输出 16 //j, k, l := 3, 4, 5 17 //x := [3]*int{&j, &k, &l} 18 x := [3]*int{&m[0], &m[1], &m[2]} 19 fmt.Printf("x:%v,%v,%v\n", x[0], x[1], x[2]) 20 fmt.Printf("*x:%v,%v,%v\n", *x[0], *x[1], *x[2]) 21 22 var n [3]*int 23 n = x 24 fmt.Printf("n:%v,%v,%v\n", n[0], n[1], n[2]) 25 //指向数组的指针,也即二级指针的使用 26 y := []*[3]*int{&x} 27 fmt.Printf("y:%v,%v\n", y, y[0]) 28 fmt.Printf("*y[0]:%v\n", *y[0]) 29 fmt.Printf("*y[][]:%v,%v,%v\n", *y[0][0], *y[0][1], *y[0][2]) 30 /* 31 *X -> v 32 [3]X -> [v0][v1][v2] 33 []X -> [v0]...[vi] 34 [3]*X -> [p0][p1][p2] 35 | | | 36 j k l 37 []*[3]*X -> [n0]...[ni] 38 | ... | 39 [p0]->j 40 [p1]->k 41 [p2]->l 42 */ 43 } 44 45 type Student struct { 46 name string 47 id int 48 score uint 49 } 50 51 func memery_test() { 52 //new分配出来的数据是指针形式 53 p := new(Student) 54 p.name = "China" 55 p.id = 63333 56 p.score = 99 57 fmt.Println(*p) 58 //var定义的变量是数值形式 59 var st Student 60 st.name = "Chinese" 61 st.id = 666333 62 st.score = 100 63 fmt.Println(st) 64 //make分配slice、map和channel的空间,并且返回的不是指针 65 var ptr *[]Student 66 fmt.Println(ptr) //ptr == nil 67 ptr = new([]Student) //指向一个空的slice 68 fmt.Println(ptr) 69 *ptr = make([]Student, 3, 100) 70 fmt.Println(ptr) 71 stu := []Student{{"China", 3333, 66}, {"Chinese", 4444, 77}, {"Chince", 5555, 88}} 72 fmt.Println(stu) 73 }
有疑问加站长微信联系(非本文作者)