Address of a temporary in Go?

后端 未结 8 761
不知归路
不知归路 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 14:11

    You can't get the reference of the result directly when assigning to a new variable, but you have idiomatic way to do this without the use of a temporary variable (it's useless) by simply pre-declaring your "b" pointer - this is the real step you missed:

    func a() string {
        return "doesn't matter"
    }
    
    b := new(string) // b is a pointer to a blank string (the "zeroed" value)
    *b = a()         // b is now a pointer to the result of `a()`
    

    *b is used to dereference the pointer and directly access the memory area which hold your data (on the heap, of course).

    Play with the code: https://play.golang.org/p/VDhycPwRjK9

提交回复
热议问题