Assign a time.Date to a *time.Time pointer to test a JSON deserialization

Issue

I have a struct, where one of the fields was declared as String, but it was intended to store a Time. Therefore I changed it to *time.Time (see the commit), note the use of a pointer to bypass the issue where ",omitempty" doesn’t really omit the value in case of an blank date.

So far so good. The problem is that now I’m trying to write a code that tests the correct deserialization of the JSON string, but I can’t compare the result with

want := Record{Id: 1539, UpdatedAt: time.Date(2014, 01, 15, 22, 03, 04, 0, time.UTC)}

because UpdatedAt is expected to be a pointer *time.Time, whereas time.Date returns a time.Time.

I can’t use

want := Record{Id: 1539, UpdatedAt: &time.Date(2014, 01, 15, 22, 03, 04, 0, time.UTC)}

because it is indeed rejected (it expects a pointer, I try to assign a struct)

cannot take the address of time.Date(2014, 1, 15, 22, 3, 3, 0, time.UTC)

Here’s my question. Is there a way to create a Record with a time.Date on the fly (hence without assigning the time.Date to a variable and then get the pointer) and/or a workaround for the issue that guarantees I can have a proper nil value assigned when the object is serialized/deserialized and the date is blank?

Solution

You can’t take the address of a function return value because you can only take the address of something that can be assigned to.

Think of it this way: if you store the result in variable, you can then take the address of that variable, but if you don’t, then there’s nothing you can take the address from.

Answered By – rvignacio

Answer Checked By – Marilyn (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.