Address of a temporary in Go?

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

    At the time of writing this, none of the answers really explain the rationale for why this is the case.

    Consider the following:

    
    func main() {
        m := map[int]int{}
        val := 1
        m[0] = val
        v := &m[0] // won't compile, but let's assume it does 
        delete(m, 0)
        fmt.Println(v)
    }
    

    If this code snippet actually compiled, what would v point to!? It's a dangling pointer since the underlying object has been deleted.

    Given this, it seems like a reasonable restriction to disallow addressing temporaries

提交回复
热议问题