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 ;-)
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.
Pointers can be dereferenced by adding an asterisk * before a pointer.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With