贺胖娇的编程之旅......

学习go_20220806_扩展_指针

2022.08.06

参考文档:
Go语言指针

获取变量在内存中的地址

例如:

func TestGetValAddr(t *testing.T) {
	a := 120
	t.Logf("the addr of a is : %v", &a)
}

输出:the addr of a is : 0xc00000a338,其中地址不是固定的

什么是指针

一个指针变量指向了一个值的内存地址,在指针变量前加上*获取指针变量的值

指针使用流程

1 定义指针变量。
2 为指针变量赋值。
3 访问指针变量中指向地址的值。

func TestNilPointer(t *testing.T) {
	var p *int
	t.Logf("p is %v\n", p) // p is <nil>
	//t.Logf("p origin is %v\n", *p) // panic runtime error: invalid memory address or nil pointer
	if p == nil {
		t.Log("p is nil") // yes! p is nil
	}
	var ptr *int
	a := 20
	ptr = &a
	t.Logf("ptr is %v\n", ptr) // ptr is 0xc00000a368
	t.Logf("*ptr is %v\n", *ptr) // *ptr is 20
}

空指针

当一个指针被定义后没有分配到任何变量时,它的值为 nil。 nil 指针也称为空指针。 nil在概念上和其它语言的null、None、nil、NULL一样,都指代零值或空值。 一个指针变量通常缩写为 ptr。

对普通地址转化:unsafe.Pointer()

func TestUnsafePointer(t *testing.T) {
	type Student struct {
		Name string
		Age  int8
	}
	studentA := Student{Name: "Tom", Age: 12}
	studentB := Student{Name: "jerry", Age: 13}
	t.Logf("studentA's age is %d and name is %s\n", studentA.Age, studentA.Name)
	t.Logf("studentB's age is %d and name is %s\n", studentB.Age, studentB.Name)
	t.Logf("studentA's age val addr: %v\n", unsafe.Pointer(&studentA.Age))
	t.Logf("studentA's name val addr: %v\n", unsafe.Pointer(&studentA.Name))
}
发表评论