Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I get the address of a type conversion in Go?

Tags:

go

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?

like image 772
handora Avatar asked Jan 29 '23 16:01

handora


1 Answers

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
like image 96
peterSO Avatar answered Feb 02 '23 09:02

peterSO