2017-02-27 75 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),所以我認爲這是要走的路。 –