golang "%p"学习记录随笔

  对于获取slice的指针地址, 通过unsafe.Pointer 和 "%p"占位符两种方式得到的地址是不同的

  

	s := make([]int, 1)
	t.Log(unsafe.Pointer(&s),unsafe.Pointer(&(s[0])),len(s),cap(s))
	t.Logf("%p\n",s)

  unsafe.Pointer获取得到的是当前slice结构实例的指针

//runtime包下
type slice struct { array unsafe.Pointer len int cap int }

  

  而"%p"获取到的是当前slice中存储的数组指针

// reflect包下的方法
func (v Value) Pointer() uintptr { // TODO: deprecate k := v.kind() switch k { case Chan, Map, Ptr, UnsafePointer: return uintptr(v.pointer()) case Func: if v.flag&flagMethod != 0 { // As the doc comment says, the returned pointer is an // underlying code pointer but not necessarily enough to // identify a single function uniquely. All method expressions // created via reflect have the same underlying code pointer, // so their Pointers are equal. The function used here must // match the one used in makeMethodValue. f := methodValueCall return **(**uintptr)(unsafe.Pointer(&f)) } p := v.pointer() // Non-nil func value points at data block. // First word of data block is actual code. if p != nil { p = *(*unsafe.Pointer)(p) } return uintptr(p) case Slice: // 这里获取的当前slice中存储的数组引用的内存地址 return (*SliceHeader)(v.ptr).Data } panic(&ValueError{"reflect.Value.Pointer", v.kind()}) }

  

 

posted @ 2020-07-30 17:19  郭星  阅读(942)  评论(1)    收藏  举报