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