Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to "cast" a pointer back to a value in Golang?

Tags:

go

I'm using time.Time as a pointer in one of my structs. Eg

type struct Example{     CreatedDate *time.Time } 

I'm using the pointer, so I can pass nil to the struct, if no date exists.

This does however pose a problem now, since I need to use the time.Since(then) function which does not accept the pointer as the parameter, but takes a time.Time instead.

So...

It's quite easy to put "&" in front of a struct eg. &time.Time, but if you have a pointer, how can you reverse it, back into eg. a type of time.Time?

Eg. (does not work, but might give you an idea of what I mean)

var t *time.Time = &time.Now() var t2 time.Time = t.(time.Time) 

I hope you can help. The question feels quite silly, since I can't find anything about it when googling. I get the feeling I'm just missing something here ;-)

like image 532
Dac0d3r Avatar asked Mar 12 '15 21:03

Dac0d3r


People also ask

How do I get pointer value in Go?

The *int is a pointer to an integer value. The & is used to get the address (a pointer) to the variable. The * character is used to dereference a pointer -- it returns a value to which the pointer references.

How do I dereference a pointer in Golang?

Pointers can be dereferenced by adding an asterisk * before a pointer.

Can you use pointers in Go?

In Go a pointer is represented using the * (asterisk) character followed by the type of the stored value. In the zero function xPtr is a pointer to an int . * is also used to “dereference” pointer variables. Dereferencing a pointer gives us access to the value the pointer points to.

What does a pointer do in Golang?

Pointers in Go programming language or Golang is a variable that is used to store the memory address of another variable. Pointers in Golang is also termed as the special variables. The variables are used to store some data at a particular memory address in the system.


1 Answers

var t *time.Time = &time.Now() var t2 time.Time = *t 

Just like in C, & means "address of" and assigns a pointer which is marked as *T. But * also means "value of", or dereferencing the pointer, and assigns the value.

This is a bit off-topic, but IMO this dual use of * is partly what gets newbies in C and friends confused about pointers.

like image 66
Not_a_Golfer Avatar answered Sep 18 '22 08:09

Not_a_Golfer