1

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?

3

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the note about the idiomatic usage of time.Time values (not pointers). The go-gitlab API I'm using uses *time.Time so I thought that was the way to go.
The only reason to have a *time.Time is if you want to convey the fact that the time has not been set e.g. reading from a DB where that column can have a NULL value. As stated, this leads to cumbersome usage on the client end. So as a compromise, one can use the IsZero() method to test if a value is set or not. go's zero-time is 0001-01-01 00:00:00 +0000 UTC - NOT epoch's 1970-01-01 - so that time is unlikely to appear in a DB.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.