编译此代码时,编译器告诉我无法获取str(s)的地址。
func main() {
s := "hello, world"
type str string
sp := &str(s)
}
所以我的问题是,类型转换是否可能会寻找新地址来查找当前的新s
,或者我还没有想过的其他内容?
答案 0 :(得分:3)
The Go Programming Language Specification
表达式通过应用指定值的计算 操作符和操作符的功能。
转换是T(x)形式的表达式,其中T是类型和x 是一个可以转换为T的表达式。
对于类型为T的操作数x,地址操作& x生成a 类型* 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