You cannot directly get the address of the function call (or, more precisely, the return value (s) of the function), as described in hobbs.
There is another way, but it is ugly
p := &[]time.Time{time.Now()}[0] fmt.Printf("%T %p\n%v", p, p, *p)
Output ( Go Playground ):
*time.Time 0x10438180 2009-11-10 23:00:00 +0000 UTC
Here, a struct with a literal containing one element (the return value is time.Now() ), the fragment is indexed (the 0th element), and the address of the time.Now() element is taken.
So it’s better to just use a local variable:
t := time.Now() p := &t
Or helper function:
func ptr(t time.Time) *time.Time { return &t } p := ptr(time.Now())
Which can also be a one-line anonymous function:
p := func() *time.Time { t := time.Now(); return &t }()
Or as an alternative:
p := func(t time.Time) *time.Time { return &t }(time.Now())
See even more alternatives:
How do I make * int64 literal in Go?
Also see the related question: How can I save a link to the result of an operation in Go?
source share