I am doing some tasks at the official 'A Tour of Go' page. I have defined a custom type IPAddr which is of type byte[4].
Lets say that a value of a type IPAddr is {127, 2, 0, 1}.
I need to override the String() method so that it gets printed in the form 127.2.0.1 instead of [127, 2, 0, 1].
Here is the code and where I am stuck:
package main
import "fmt"
type IPAddr [4]byte
func (p IPAddr) String() string {
return string(p[0]) + "." + string(p[1]) + "." + string(p[2]) + "." + string(p[3]) // this here does not work.
//Even if I simply return p[0] nothing is returned back.
}
func main() {
a := IPAddr{127, 2, 54, 32}
fmt.Println("a:", a)
}
byteandint8are the same type. Type conversions liketypename(value)are only used in cases where the types in question have equivalent or very similar memory representation, e.g.string([]byte{}),int(byte(1))byte[4]is not valid Go.