Address of a temporary in Go?

后端 未结 8 875
不知归路
不知归路 2021-02-01 13:24

What\'s the cleanest way to handle a case such as this:

func a() string {
    /* doesn\'t matter */
}

b *string = &a()

This generates the

8条回答
  •  無奈伤痛
    2021-02-01 13:55

    See the relevant section of the Go language spec. & can only be used on:

    1. Something that is addressable: variable, pointer indirection, slice indexing operation, field selector of an addressable struct, array indexing operation of an addressable array; OR
    2. A composite literal

    What you have is neither of those, so it doesn't work.

    I'm not even sure what it would mean even if you could do it. Taking the address of the result of a function call? Usually, you pass a pointer of something to someone because you want them to be able to assign to the thing pointed to, and see the changes in the original variable. But the result of a function call is temporary; nobody else "sees" it unless you assign it to something first.

    If the purpose of creating the pointer is to create something with a dynamic lifetime, similar to new() or taking the address of a composite literal, then you can assign the result of the function call to a variable and take the address of that.

提交回复
热议问题