将函数返回的值分配给指针 [英] Assign value returned from function to pointer

查看:91
本文介绍了将函数返回的值分配给指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Go中,如何将函数调用返回的值分配给指针?

In Go, how do you assign a value returned by a function call to a pointer?

请考虑以下示例,请注意 time.Now() 会返回time.Time值(不是指针):

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)
}

这些都失败了:

$ 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?

推荐答案

本地变量是必需的规范.

要获取值的地址,调用函数必须将返回值复制到可寻址的内存中.有副本,但不是多余的.

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程序通常使用time.Time值.

Go programs typically work with time.Time values.

A *time.Time有时在应用程序想要区分无值和其他时间值的情况下使用.在SQL NULL和有效时间之间进行区分是一个示例.因为time.Time的零值已经过去,所以使用零值代表不值通常是很实际的.使用IsZero()方法测试零值.

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.

这篇关于将函数返回的值分配给指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆