go 何时无法取地址

2019-05-25 09:03:24 浏览数 (1)

why-cant-i-get-the-address-of-a-type-conversion-in-go

The Go Programming Language Specification

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

Conversions 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.

Address operators 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,

代码语言:javascript复制
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)
}

0 人点赞