2017-08-31 23 views
0

当我编译这段代码时,编译器告诉我我不能取str(s)的地址。为什么我不能在Go中获得类型转换的地址?

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

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

+6

A转换结果[不是寻址](https://golang.org/ref/spec#Address_operators)。 –

回答

3

The Go Programming Language Specification

Expressions

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

Conversions

换算的形式为T(x),其中T是一个类型,并且x 是可被转换为类型T.

Address operators

对于操作数的表达式的表达式x类型T,地址操作& 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 
相关问题