源地址 https://tour.go-zh.org/methods/18

一、题目描述

通过让 IPAddr 类型实现 fmt.Stringer 来打印点号分隔的地址。

例如,IPAddr{1, 2, 3, 4} 应当打印为 "1.2.3.4"

Go指南练习_Stringer

 

二、题目分析

  • 设置IPAddr类型;
  • 借助fmt.Stringer函数打印地址。

 

三、Go代码

import "fmt"

type IPAddr [4]byte

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

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

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

运行结果

Go指南练习_Stringer

 

参考文档 http://www.cplusplus.com/reference/cstdio/sprintf/

 

相关文章:

  • 2021-06-10
  • 2022-01-10
  • 2021-09-10
  • 2021-09-07
  • 2021-10-30
  • 2022-12-23
  • 2021-07-21
  • 2021-07-17
猜你喜欢
  • 2021-06-04
  • 2021-12-29
  • 2021-08-17
  • 2021-04-26
  • 2021-07-24
相关资源
相似解决方案