V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
ppolanwind

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

  •  
  •   ppolanwind · Aug 9, 2022 · 2002 views
    This topic created in 1359 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
        1
    LXJ  
       Aug 9, 2022
    uintptr(8) 可以替换成 unsafe.Sizeof(new(int))))
    MoYi123
        2
    MoYi123  
       Aug 9, 2022
    a_int, ok := s.(int) 可以类型断言啊
    picone
        3
    picone  
       Aug 10, 2022
    如果不是逼不得已,不要自己用 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   ·   Solana   ·   909 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 50ms · UTC 21:02 · PVG 05:02 · LAX 14:02 · JFK 17:02
    ♥ Do have faith in what you're doing.