Skip to content

Instantly share code, notes, and snippets.

@danimal141
Last active July 5, 2025 06:19
Show Gist options
  • Save danimal141/040a3d03598a6a51553a7a839f9d2d5a to your computer and use it in GitHub Desktop.
Save danimal141/040a3d03598a6a51553a7a839f9d2d5a to your computer and use it in GitHub Desktop.
A Tour of Go Exercise: Stringers
package main
import (
"fmt"
"strings"
"strconv"
)
type IPAddr [4]byte
func (ip IPAddr) String() string {
s := make([]string, len(ip))
for i, val := range ip {
s[i] = strconv.Itoa(int(val))
}
return strings.Join(s, ".")
}
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)
}
}
@priyanshoon
Copy link

package main

import "fmt"

type IPAddr [4]byte

// TODO: Add a "String() string" method to IPAddr.
func (ip IPAddr) String() string {
	var ipFinal string = ""
	for i := range ip {
		if i < 3 {
			ipFinal = ipFinal + fmt.Sprintf("%d", ip[i]) + "."
		} else {
			ipFinal = ipFinal + fmt.Sprintf("%d", ip[i])
		}
	}
	return ipFinal
}

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)
	}
}

@filipcvejic
Copy link

package main

import (
	"fmt"
	"strings"
	"strconv"
)

type IPAddr [4]byte

// TODO: Add a "String() string" method to IPAddr.
func (ip IPAddr) String() string {
	s := make([]string, len(ip))
	for i, val := range ip {
		s[i] = strconv.Itoa(int(val))
	}
	return strings.Join(s, ".")
}

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)
	}
}

@duj4
Copy link

duj4 commented Jul 5, 2025

I'm using append instead of concat string

package main

import (
	"fmt"
	"strings"
	"strconv"
)

type IPAddr [4]byte

func (ip IPAddr) String() string {
	s := make([]string, len(ip))
	
	for _, v := range ip {
		s = append(s, strconv.Itoa(int(v)))
	} 
	
	return strings.Join(s, ".")
}

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)
	}
}

I think it'd be better to declare the slice s like make([]string, 0, len(ip)). Otherwise, the output would be like "....127.0.0.1" as the append will add the digit from index 4.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment