Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go receiver implicit pointer conversion not working

Tags:

go

I'm learning Go, and I was following the go tour.

In the exercise about Stringer, here, Implementing the function with a *IPAddr receiver doesn't seem to work, which the go tour describes as should work.

package main

import "fmt"

type IPAddr [4]byte

// TODO: Add a "String() string" method to IPAddr.
func (ip *IPAddr) String() string {
    return fmt.Sprintf("%v.%v.%v.%v", ip[0], ip[1], ip[2], ip[3])
}
func main() {
    hosts := map[string]IPAddr{
        "loopback":  {127, 0, 0, 1},
        "googleDNS": {8, 8, 8, 8},
    }
    for name, ip := range hosts {
        fmt.Printf("%v: %v\n", name, ip)
    }
}

Output is:

loopback: [127 0 0 1]
googleDNS: [8 8 8 8]

But changing String() string to func (ip IPAddr) from func (ip *IPAddr) gives the correct output:

loopback: 127.0.0.1
googleDNS: 8.8.8.8

Why is that?

like image 357
Tejas Avatar asked Feb 03 '26 22:02

Tejas


1 Answers

Implementing func (ip IPAddr) String() will work for both IPAddr and *IPAddr types.

Implementing func (ip *IPAddr) String will only work for *IPAddr.

like image 105
Mike Rapadas Avatar answered Feb 05 '26 13:02

Mike Rapadas