D
D
danforth2016-12-01 22:54:56
go
danforth, 2016-12-01 22:54:56

How to implement an interface in Go?

Hello!
Learning Go, got to interfaces, stuck on this exercise.
The task is this: there is a type IPAddr based on the base type array of bytes []byte. This type will store the IP address.
You need to implement the fmt.Stringer interface, which has one String() string method . At the end, IP should be displayed through a dot, like this: 8.8.8.8, but in my console (and in the sandbox a little lower) everything pours out like this [8 8 8 8]
Here is my code ( sandbox ):

package main

import "fmt"

type IPAddr [4]byte

// TODO: Add a "String() string" method to IPAddr.
func (i *IPAddr) String() string {
  return fmt.Sprintf("%d.%d.%d.%d", i[0], i[1], i[2], i[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)
  }
}

How can we still implement the fmt.Stringer interface? Obviously, I just get %v, and not the result of the String() method

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
evnuh, 2016-12-01
@danforth

You have implemented an interface for the type "pointer to IPAddr" and you are printing out the type "IPAddr".
This comes with a complication due to the double standards adopted in Go, although they are logical. Remember forever:
That is, in your case, everything would work if the types matched correctly AND if the situation was wrong, opposite to your code - if you implemented an interface for the type itself, but tried to print a pointer to it.
This is explained simply - if the method is implemented for a pointer, it most likely can change something in the object by this pointer, therefore, passing the object by value, and not by pointer, it would change not in the object itself, but in its copy, which would be done when passing by value. This is clearly not what the method writer expected.
In the opposite case, if the method is defined for the type by value, and not by pointer, it is obvious that the method does not change anything in the value itself (if it tried, it would change again in a copy of the value). And since it doesn’t change anything there, we can safely pass our object under the link.
Everything is explained here in detail: https://github.com/golang/go/wiki/MethodSets

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question