dsfdf854456 2012-10-14 10:03
浏览 45
已采纳

直接在Go中的堆上构造基本类型?

How do I construct a primitive integer type directly on the heap in Go?

For composite literals, the following syntax is supported:

return &File{fd, name, nil, 0}

But no such equivalent seems to exist for int and friends:

Size: &uint64(entry.FileInfo.Size()),

d:\gopath\src\bitbucket.org\anacrolix\dms\dlna\dms\dms.go:271: cannot take the address of uint64(entry.FileInfo.Size())

  • 写回答

2条回答 默认 最新

  • douxing2652 2012-10-14 12:23
    关注

    Address operators

    For an operand x of type T, the address operation &x generates a pointer of type *T to x. The operand must be addressable, that is, either a variable, pointer indirection, or slice indexing operation; or a field selector of an addressable struct operand; or an array indexing operation of an addressable array. As an exception to the addressability requirement, x may also be a composite literal.

    Primitive integer types are not addressable. If the integer is a register variable, there is no memory address. If the integer is a constant, providing its memory address would allow it to be modified.

    Therefore, create an integer type variable and take its address or use an integer pointer type. For example,

    package main
    
    import "fmt"
    
    func main() {
        var i int = 42
        var pi = &i
        j := int(7)
        pj := &j
        var pk = new(int)
        k := *pk
        fmt.Println(i, pi)
        fmt.Println(j, pj)
        fmt.Println(k, pk)
    }
    

    Output:

    42 0xf840043100
    7 0xf840043108
    0 0xf840043110
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 虚拟机打包apk出现错误
  • ¥30 最小化遗憾贪心算法上界
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝