-2

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)
}
5
  • 4
    String conversion does not convert an integer value to decimal text as assumed by the code in the question. Use the fmt or strconv package to get decimal text. Commented Dec 20, 2020 at 22:23
  • I needed byte to String conversion Commented Dec 20, 2020 at 23:04
  • 1
    @PanagiotisBougioukos byte and int8 are the same type. Type conversions like typename(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)) Commented Dec 20, 2020 at 23:06
  • Possible duplicate of Convert a byte to a string in Go. This question wants "," instead of "." separators, but is otherwise the same. Commented Dec 20, 2020 at 23:33
  • "I have defined a custom type IPAddr which is of type byte[4]." -- byte[4] is not valid Go. Commented Dec 21, 2020 at 8:56

1 Answer 1

4

By using the string conversion the values are getting casted in a way that you are not expected. You can notice that 54 is printing as 6 since the ascii value of 54 corresponds to "6".

Here is a way to get the expected result using fmt.

package main

import "fmt"

type IPAddr [4]byte

func (p IPAddr) String() string {
   return fmt.Sprintf("%d.%d.%d.%d", p[0], p[1], p[2], p[3]) 
}

func main() {
    a := IPAddr{127, 2, 54, 32}
    fmt.Println("a:", a)
}
Sign up to request clarification or add additional context in comments.

1 Comment

This solves the problem thanks. Glad to know that we must use this Sprintf for string conversions.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.