英文:
Assign value returned from function to pointer
问题
在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() // 失败,第15行
f.t = &time.Now() // 失败,第17行
tmp := time.Now() // 解决方法
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()
是否真的需要一个局部变量?这样做是否会产生不必要的复制?
英文:
In Go, how do you assign a value returned by a function call to a pointer?
Consider this example, noting that time.Now()
returns a time.Time
value (not pointer):
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)
}
These both fail:
<!-- language: none -->
$ 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()
Is a local variable truly required? And doesn't that incur an unnecessary copy?
答案1
得分: 6
本地变量是必需的根据规范。
要获取值的地址,调用函数必须将返回值复制到可寻址的内存中。这里有一个复制,但它并不是多余的。
Go程序通常使用time.Time
值。
在某些情况下,会使用*time.Time
,以便应用程序可以区分没有值和其他时间值。区分SQL NULL和有效时间就是一个例子。由于time.Time
的零值在过去很久以前,通常可以使用零值来表示没有值。使用IsZero()
方法来测试是否为零值。
英文:
The local variable is required per the specification.
To get the address of a value, the calling function must copy the return value to addressable memory. There is a copy, but it's not extra.
Go programs typically work with time.Time
values.
A *time.Time
is sometimes used situations where the application wants to distinguish between no value and other time values. Distinguishing between a SQL NULL and a valid time is an example. Because the zero value for a time.Time
is so far in the past, it's often practical to use the zero value to represent no value. Use the IsZero()
method to test for a zero value.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论