How to get the pointer of return value from function call?

后端 未结 3 2050
有刺的猬
有刺的猬 2020-11-27 18:09

I just need a pointer to time.Time, so the code below seems invalid:

./c.go:5: cannot take the address of time.Now()

I just wond

3条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-27 18:26

    The probably unsatisfying answer is "you can't do it because the spec says so." The spec says that to use & on something it has to be addressable or a compound literal, and to be addressable it has to be "a variable, pointer indirection, or slice indexing operation; or a a field selector of an addressable struct operand; or an array indexing operation of an addressable array." Function calls and method calls are definitely not on the list.

    Practically speaking, it's probably because the return value of a function may not have a usable address; it may be in a register (in which case it's definitely not addressable) or on the stack (in which case it has an address, but one that won't be valid if it's put in a pointer that escapes the current scope. To guarantee addressability, Go would have to do pretty much the exact equivalent of assigning it to a variable. But Go is the kind of language that figures that if it's going to allocate storage for a variable it's going to be because you said to, not because the compiler magically decided to. So it doesn't make the result of a function addressable.

    Or I could be over-thinking it and they simply didn't want to have a special case for functions that return one value versus functions that return multiple :)

提交回复
热议问题