time.Now()
returns a value of type time.Time
, which is not *time.Time
.
Note that you also cannot take the address of the return values of function calls, you can't do &time.Now()
either. For details, see How to get the pointer of return value from function call?
What you may do is use a variable of type time.Time
and take its address:
var t = time.Now()
payload:= &device.Payload{
Timestamp: &t,
}
Another "popular" option is to create a helper function to return the address of a time.Time
value (to which you may pass the return value of a function call directly):
func timePtr(t time.Time) *time.Time {
return &t
}
payload:= &device.Payload{
Timestamp: timePtr(time.Now()),
}
For details and other options, see How do I do a literal *int64 in Go?
I assume you want a pointer because you want to allow "missing time" option, which is necessary for the encoding/json
package to respect a "missing time" (details: JSON omitempty With time.Time Field). Note that in other cases it may not be necessary to automatically turn to pointer: you may use the zero value of time.Time
(which is a struct) to indicate the "missing time" state. To easily tell if a time.Time
is its zero value, you may use Time.IsZero()
. See related: Idiomatic way to represent optional time.Time in a struct