Copying Pointers in Go
Over a year ago I was trying to make a copy of a *url.URL
and ended up with
this quite nasty way to do
so.
I even applied this to
maskpass
, a
small package that masks the password of an url.URL to make it log-friendly.
But today, looking for a nice clean way to do so in a PR being sent to Go I
realized tmp := *src
does the work nicely.
package main
import (
"fmt"
"net/url"
)
func main() {
src, _ := url.Parse("http://user:[email protected]/")
tmp := *src
tmp.User = url.UserPassword(tmp.User.Username(), "xxxxx")
fmt.Printf("%s, %s", src.String(), tmp.String())
}
https://play.golang.org/p/F4vaqN3wC_H
What this shows is that changing values in tmp
won’t change the values in
src
so you have effectively copied the values of the source pointer to a new
pointer.
So, if you’re looking for a clean way to copy the value of a pointer in Go, hopefully, this will help you.