dongyoudi1342 2017-08-31 02:44
浏览 30
已采纳

为什么我无法在Go中获得类型转换的地址?

When I compile this code, the compiler tells me that I cannot take the address of str(s).

func main() {
    s := "hello, world"
    type str string
    sp := &str(s)
}

So my question is whether a type conversion may look for a new address to locate the current new s, or something else that I haven't thought of?

  • 写回答

1条回答 默认 最新

  • dousuie2222 2017-08-31 07:31
    关注

    The Go Programming Language Specification

    Expressions

    An expression specifies the computation of a value by applying operators and functions to operands.

    Conversions

    Conversions are expressions of the form T(x) where T is a type and x is an expression that can be converted to type T.

    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 (possibly parenthesized) composite literal. If the evaluation of x would cause a run-time panic, then the evaluation of &x does too.

    Expressions are temporary, transient values. The expression value has no address. It may be stored in a register. A comversion is an expression. For example,

    package main
    
    import (
        "fmt"
    )
    
    func main() {
        type str string
        s := "hello, world"
        fmt.Println(&s, s)
    
        // error: cannot take the address of str(s)
        sp := &str(s)
        fmt.Println(sp, *sp)
    }
    

    Output:

    main.go:13:8: cannot take the address of str(s)
    

    To be addressable a value must be persistent, like a variable. For example,

    package main
    
    import (
        "fmt"
    )
    
    func main() {
        type str string
        s := "hello, world"
        fmt.Println(&s, s)
    
        ss := str(s)
        sp := &ss
        fmt.Println(sp, *sp)
    }
    

    Output:

    0x1040c128 hello, world
    0x1040c140 hello, world
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP