在Go中,如何将函数调用返回的值赋给指针?将函数返回的值赋给指针
下面这个例子,并指出time.Now()
返回time.Time
值(不是指针):
package main
import (
"fmt"
"time"
)
type foo struct {
t *time.Time
}
func main() {
var f foo
f.t = time.Now() // Fail line 15
f.t = &time.Now() // Fail line 17
tmp := time.Now() // Workaround
f.t = &tmp
fmt.Println(f.t)
}
这些都失败:
$ go build
# _/home/jreinhart/tmp/go_ptr_assign
./test.go:15: cannot use time.Now() (type time.Time) as type *time.Time in assignment
./test.go:17: cannot take the address of time.Now()
确实是需要一个本地变量?这不会产生不必要的副本吗?
我相信本地变量是必需的。所以在内存空间分配time.Now()。 f.t被定义为一个指针,但它没有,因为它没有被初始化,所以在内存中没有位置。然后你通过引用分配tmp,它告诉f.t成为tmp。所以你不会复制任何东西。 – reticentroot
查看可能的重复解释和替代方法:[我如何在Go中执行literal * int64?](http://stackoverflow.com/questions/30716354/how-do-i-do-a-literal-int64-in -go/30716481#30716481);和[如何在Go中存储对操作结果的引用?](http://stackoverflow.com/questions/34197248/how-can-i-store-reference-to-the-result-of-an-操作进行中去/ 34197367#34197367);和[如何从函数调用返回值的指针?](http://stackoverflow.com/questions/30744965/how-to-get-the-pointer-of-return-value-from-function-call/ 30751102#30751102) – icza
谢谢@icza,我肯定花了时间寻找这个问题,但我清楚地写了不同的表述。 –