Last active
July 5, 2025 06:19
-
-
Save danimal141/040a3d03598a6a51553a7a839f9d2d5a to your computer and use it in GitHub Desktop.
A Tour of Go Exercise: Stringers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think it'd be better to declare the
slice slikemake([]string, 0, len(ip)). Otherwise, the output would be like "....127.0.0.1" as theappendwill add the digit from index 4.