dongyuans61046 2017-02-27 02:15
浏览 38
已采纳

将函数返回的值分配给指针

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:

$ 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条回答 默认 最新

  • douxieshang5577 2017-02-27 02:26
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?