Golang Non-Struct Type Pointer Receiver

I created a custom type based on the Golang type net.IP. I was surprised that a method declared using the receiver of a pointer to my user type cannot change the value that the receiver points to.

The variable uin this code fragment remains nilafter the call u.defaultIP(). IP can be changed if I changed my own type to a structure with an IP field, and the method is defined using the receiver of a pointer to the structure. What am I missing? An executable example can be 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
}
+4
source share
3 answers

You must dereference values ​​before setting u.

In your example, change

defaultIP := userIP("127.0.0.1")
u = &defaultIP

to

*u = userIP("127.0.0.1")

: https://play.golang.org/p/ycCLT0ed9F

+5

TL; DR: , . , . .

, , , , , .

, u main() defaultIP(). , , u defaultIP(). .

func main() {
  var u *userIP         
  u.defaultIP()

  fmt.Printf("main(): address of pointer is %v\n", &u)
  fmt.Printf("main(): user IP address is %v\n", u)
}

type userIP net.IP

func (u *userIP) defaultIP() {  
  defaultIP := userIP("127.0.0.1")
  u = &defaultIP

  fmt.Printf("defaultIP(): address of pointer is %v\n", &u)
  fmt.Printf("defaultIP(): user IP address is %s\n", *u)
}

, , u defaultIP().

, , IP ? , u , ip . .

func main() {
  u := &userInfo{}
  u.defaultIP()

  fmt.Printf("main(): address of pointer is %v\n", &u)
  fmt.Printf("main(): user IP address is %s\n", u.ip)
}

type userInfo struct{
  ip net.IP
}

func (u *userInfo) defaultIP() {
  u.ip = net.ParseIP("127.0.0.1")
  fmt.Printf("defaultIP(): address of pointer is %v\n", &u)
  fmt.Printf("defaultIP(): user IP address is %s\n", u.ip)
}

, (x.y). ,

. x , x.y (x).y; y , x.y.z ((* x).y).z .. x * A, A , x.f (* x.A).f.

, , u.ip dereferences u ip, (*u).ip.

+1

:

1- : net.ParseIP("127.0.0.1")
( Go:

package main

import (
    "fmt"
    "net"
)

type userIP net.IP

func main() {
    var u userIP
    u.defaultIP()
    fmt.Println(u)
}

func (u *userIP) defaultIP() {
    *u = userIP(net.ParseIP("127.0.0.1"))
}

:

[0 0 0 0 0 0 0 0 0 0 255 255 127 0 0 1]

2 ( Go):

package main

import (
    "fmt"
    "net"
)

type userIP net.IP

func main() {
    u := make(userIP, 4)
    u.defaultIP()
    fmt.Printf("%v\n", u)
}

func (u userIP) defaultIP() {
    u[0], u[1], u[2], u[3] = 127, 0, 0, 1
}

, net.IP []byte, . net.IP :

IP - IP-, . 4- (IPv4) 16- (IPv6) .

0

Source: https://habr.com/ru/post/1652266/


All Articles