Address of a temporary in Go?

后端 未结 8 744
不知归路
不知归路 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:54

    The address operator returns a pointer to something having a "home", e.g. a variable. The value of the expression in your code is "homeless". if you really need a *string, you'll have to do it in 2 steps:

    tmp := a(); b := &tmp
    

    Note that while there are completely valid use cases for *string, many times it's a mistake to use them. In Go string is a value type, but a cheap one to pass around (a pointer and an int). String's value is immutable, changing a *string changes where the "home" points to, not the string value, so in most cases *string is not needed at all.

提交回复
热议问题