I found that following code in Golang works:
type user struct {
name *string
email *string
}
func foo() (*user, error) {
var myname string
var myemail string
// Some code here to fetch myname and myemail
u := user{}
u.name = &myname
u.email = &myemail
return &u, nil
}
I am aware that it is safe to return a pointer to local variable as a local variable will survive the scope of the function, so I am not concerned about returning &u
from the function foo()
.
What I am concerned are the assignments:
u.name = &myname
u.email = &myemail
Is it just by chance that Go compiler assigns u.name
and u.email
in heap so that I am able to access it outside the function, or there is some guarantee it will always work (via pointer escape analysis mechanism)?
if the above code is not safe, I would fall back to something like following:
u.name = new(string)
*u.name = myname
...