Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

json

pointers

go

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?

like image 564
Simone Carletti Avatar asked Jan 16 '15 17:01

Simone Carletti


2 Answers

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.

like image 131
rvignacio Avatar answered Nov 13 '22 21:11

rvignacio


You want to store the date value in a variable first and then use the pointer of the variable.

myDate := time.Date(2014, 01, 15, 22, 03, 04, 0, time.UTC)
want := Record{Id: 1539, UpdatedAt: &myDate}
like image 20
Darren Coxall Avatar answered Nov 13 '22 21:11

Darren Coxall