【问题标题】:Why can't I get the address of a type conversion in Go?为什么我无法在 Go 中获取类型转换的地址?
【发布时间】:2017-08-31 02:44:53
【问题描述】:

当我编译这段代码时,编译器告诉我无法获取 str(s) 的地址

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

所以我的问题是类型转换是否会寻找一个新地址来定位当前新的s,或者我没有想到的其他东西?

【问题讨论】:

标签: go


【解决方案1】:

The Go Programming Language Specification

Expressions

表达式通过应用指定值的计算 运算符和函数到操作数。

Conversions

转换是 T(x) 形式的表达式,其中 T 是一个类型,x 是一个可以转换为T类型的表达式。

Address operators

对于 T 类型的操作数 x,地址操作 &x 生成一个 *T 类型的指针指向 x。操作数必须是可寻址的,即 变量、指针间接或切片索引操作; 或可寻址结构操作数的字段选择器;或数组 可寻址数组的索引操作。作为一个例外 可寻址性要求,x 也可以是(可能是括号) 复合字面量。如果 x 的评估会导致运行时 恐慌,那么 &x 的评估也是如此。

表达式是临时的、瞬态的值。表达式值没有地址。它可以存储在寄存器中。转换是一种表达。例如,

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)
}

输出:

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

要可寻址,值必须是持久的,就像变量一样。例如,

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)
}

输出:

0x1040c128 hello, world
0x1040c140 hello, world

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-20
    • 1970-01-01
    • 2019-06-23
    • 2011-12-20
    • 2015-05-24
    • 2017-12-05
    相关资源
    最近更新 更多