5

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

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?

1

1 Answer 1

8

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,

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

Output:

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

Output:

0x1040c128 hello, world
0x1040c140 hello, world

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.