douxi3404 2019-01-24 02:41
浏览 240

我可以在Go中使用unsafe.Pointer将* interface {}转换为* int吗

I am making a memory pool in Go.
I am doing so because implicit converting int to interface{} will trigger a memory allocation.I want to avoid the allocation.
I want to allocate several types of pointers in one pool.
The pool is something like this.

type creator struct{
    buf []interface{}
}
func (cr *creator) Create()*interface{}{
    if len(cr.buf)==0{
        cr.buf=make([]interface{},256)
    }
    current:=&cr.buf[0]
    cr.buf=cr.buf[1:]
    return current
}

func (cr *creator)CreateInt()*int{
    pointer:=cr.Create()
    return (*int)(unsafe.Pointer(pointer))   // <-- right or wrong?
}

Is the code valid?

  • 写回答

1条回答 默认 最新

  • drs7798 2019-01-24 03:20
    关注

    You have *interface {} and you want to pretend that it is *int! How is that going to work?

    package main
    
    import (
        "fmt"
        "unsafe"
    )
    
    func main() {
        var cr creator
        pointer := cr.CreateInt()
        fmt.Printf("%T
    ", pointer) // *int
    }
    
    type creator struct {
        buf []interface{}
    }
    
    func (cr *creator) Create() *interface{} {
        if len(cr.buf) == 0 {
            cr.buf = make([]interface{}, 256)
        }
        current := &cr.buf[0]
        cr.buf = cr.buf[1:]
        return current
    }
    
    func (cr *creator) CreateInt() *int {
        pointer := cr.Create()
        fmt.Printf("%T
    ", pointer)            // *interface {}
        return (*int)(unsafe.Pointer(pointer)) // *interface {} to *int
    }
    

    Playground: https://play.golang.org/p/TLF7kbYPA0M

    Output:

    *interface {} 0x452000
    *int 0x452000
    
    评论

报告相同问题?

悬赏问题

  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染