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)
}
Run Code Online (Sandbox Code Playgroud)
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?
表达式通过将运算符和函数应用于操作数来指定值的计算。
转换是 T(x) 形式的表达式,其中 T 是一个类型,x 是一个可以转换为 T 类型的表达式。
对于 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)
}
Run Code Online (Sandbox Code Playgroud)
输出:
main.go:13:8: cannot take the address of str(s)
Run Code Online (Sandbox Code Playgroud)
要可寻址,值必须是持久的,就像变量一样。例如,
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)
}
Run Code Online (Sandbox Code Playgroud)
输出:
0x1040c128 hello, world
0x1040c140 hello, world
Run Code Online (Sandbox Code Playgroud)