The Go Programming Language
› http://golang.org/
› Go Playground
Go Projects
› Revel Web Framework
ppolanwind

Golang 中怎么获得接口中存储的数据指针?

  •  
  •   ppolanwind · Aug 9, 2022 · 2484 views
    This topic created in 1555 days ago, the information mentioned may be changed or developed.

    目前我是这样做的,在做指针偏移的时候直接加上 8 个字节不知道会不会存在隐含的 Bug ,是否还有别的方法?

    func main() {
    	var a int = 5
    	var s interface{}
    	s = &a
    	p := *(*uintptr)(unsafe.Pointer(uintptr(unsafe.Pointer(&s)) + uintptr(8)))
    	fmt.Printf("%p\n", unsafe.Pointer(p))
    	fmt.Printf("%p\n", &a)
    }
    
    

    求各位大佬指点。

    3 replies  •  2022-08-10 09:34:07 +08:00
    LXJ
    LXJ
    Aug 9, 2022
    1
    uintptr(8) 可以替换成 unsafe.Sizeof(new(int))))
    MoYi123
    MoYi123
    Aug 9, 2022
    2
    a_int, ok := s.(int) 可以类型断言啊
    picone
    picone
    Aug 10, 2022
    3
    如果不是逼不得已,不要自己用 unsafe.Pointer 。可以看看 [refelct2]( https://pkg.go.dev/github.com/modern-go/reflect2#readme-reflect2-get-set-unsafe-pointer) 这个包能拿到 `unsafe.Pointer`
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   1599 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 16:26 · PVG 00:26 · LAX 08:26 · JFK 11:26
    ♥ Do have faith in what you're doing.