go - Golang Non-Struct Type Pointer Receiver -


i created custom type based on golang net.ip type. surprised me method declared pointer receiver custom type can't modify value receiver points.

the u variable in code snippet remains nil after calling u.defaultip(). ip can modified if changed custom type struct ip field , method defined pointer receiver struct. missing? executable example can found here.

type userip net.ip  func main() {   var u *userip   u.defaultip()   fmt.printf("%v\n", u)  }  func (u *userip) defaultip() {   defaultip := userip("127.0.0.1")   u = &defaultip } 

you need dereference u before setting it's value.

from example, change

defaultip := userip("127.0.0.1") u = &defaultip 

to

*u = userip("127.0.0.1") 

for example updated , working: https://play.golang.org/p/ycclt0ed9f


Comments

Popular posts from this blog

mysql - Dreamhost PyCharm Django Python 3 Launching a Site -

java - Sending SMS with SMSLib and Web Services -

java - How to resolve The method toString() in the type Object is not applicable for the arguments (InputStream) -