Reputation: 954
I have a struct defined in some device.go
file
type Payload struct {
...
Timestamp *time.Time `json:"timestamp,omitempty"`
...
}
Now I want to Initialize this struct in some other file and I'm trying this:
payload:= &device.Payload{
....
Timestamp: time.Now(), // throws error
... //other initializations work fine
}
cannot use time.Now() (value of type time.Time) as *time.Time value in struct literal
I want to initialize the variable as the current UTC time. I'm new to golang. How do I do that?
Upvotes: 2
Views: 15378
Reputation: 417472
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
Upvotes: 9
Reputation: 76
time.Now() returns a Time value, but your struct is looking for a pointer. Change your struct to
type Payload struct {
...
Timestamp time.Time `json:"timestamp,omitempty"`
...
}
from the docs (https://pkg.go.dev/time#Time):
Programs using times should typically store and pass them as values, not pointers. That is, time variables and struct fields should be of type time.Time, not *time.Time.
Upvotes: 2