2017-02-27 52 views
1

在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() 

确实是需要一个本地变量?这不会产生不必要的副本吗?

+0

我相信本地变量是必需的。所以在内存空间分配time.Now()。 f.t被定义为一个指针,但它没有,因为它没有被初始化,所以在内存中没有位置。然后你通过引用分配tmp,它告诉f.t成为tmp。所以你不会复制任何东西。 – reticentroot

+2

查看可能的重复解释和替代方法:[我如何在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

+0

谢谢@icza,我肯定花了时间寻找这个问题,但我清楚地写了不同的表述。 –

回答

6

需要本地变量per the specification

要获取值的地址,调用函数必须将返回值复制到可寻址内存。有一个副本,但它不是额外的。

Idiomatic Go程序使用time.Time值。与*time.Time合作很少见。

+0

感谢关于'time.Time'值(不是指针)习惯用法的说明。我使用的'go-gitlab' API使用['* time.Time'](https://github.com/xanzy/go-gitlab/blob/442ae38dfd2f6a1e94d5f384bb6df1784395e732/builds.go#L46),所以我认为这是要走的路。 –