为什么我无法在Go中获得类型转换的地址? [英] Why can't I get the address of a type conversion in Go?

查看:75
本文介绍了为什么我无法在Go中获得类型转换的地址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

所以我的问题是类型转换是否会寻找新地址来查找当前的新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?

推荐答案

Go编程语言规范

表达式

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

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

转化

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

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.

地址运算符

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

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

输出:

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

输出:

0x1040c128 hello, world
0x1040c140 hello, world

这篇关于为什么我无法在Go中获得类型转换的地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆