go stringers 练习有问题

trouble with go stringers exercise

围棋之旅中的 Stringers 练习: 对于两种不同格式的打印,我得到了两种不同的输出。我唯一改变的是格式动词。他们是 %v 和 %d。理论上,它们会给出相同的输出。但是输出的顺序也改变了,这太奇怪了。对此有什么想法吗?下面是我的代码:

package main

import "fmt"

type IPAddr [4]byte

// TODO: Add a "String() string" method to IPAddr.
func (a IPAddr)String() string{
    // Here is what I changed
    return fmt.Sprintf("%d.%d.%d.%d",a[0],a[1],a[2],a[3])
}

func main() {
    addrs := map[string]IPAddr{
        "loopback":  {127, 0, 0, 1},
        "googleDNS": {8, 8, 8, 8},
    }
    for n, a := range addrs {
        fmt.Printf("%v: %v\n", n, a)
    }
}

输出:

googleDNS: 8.8.8.8

环回:127.0.0.1

package main

import "fmt"

type IPAddr [4]byte

// TODO: Add a "String() string" method to IPAddr.
func (a IPAddr)String() string{
    // Here is what I changed
    return fmt.Sprintf("%v.%v.%v.%v",a[0],a[1],a[2],a[3])
}

func main() {
    addrs := map[string]IPAddr{
        "loopback":  {127, 0, 0, 1},
        "googleDNS": {8, 8, 8, 8},
    }
    for n, a := range addrs {
        fmt.Printf("%v: %v\n", n, a)
    }
}

输出:

环回:127.0.0.1

googleDNS: 8.8.8.8

输出的顺序也改变了。

地图未排序。

When iterating over a map with a range loop, the iteration order is not specified and is not guaranteed to be the same from one iteration to the next[1]

[1]https://blog.golang.org/go-maps-in-action#TOC_7.

除了顺序之外,我没有发现 %v%d 输出有任何区别。

package main

import "fmt"

type IPAddr [4]byte

// TODO: Add a "String() string" method to IPAddr.

func (ip IPAddr) String() string {
   var s string
   for i:= range ip{
     if(i==0){
      s +=fmt.Sprint(int(ip[i]))
     } else{
        s +="."+fmt.Sprint(int(ip[i]))
     }
  }     

  return 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)
  }
}
package main

import (
    "fmt"
)

type IPAddr [4]byte

// TODO: Add a "String() string" method to IPAddr.

func (ip IPAddr) String() string {
    
    var s string
    for _, v := range ip {
        s += fmt.Sprint(int(v)) + "."
    }
    sr := s[:len(s)-1]
    return sr
}

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