代码之家  ›  专栏  ›  技术社区  ›  Panagiotis Bougioukos

GoLang使用Stringer接口为自定义类型重写string方法(byte[4])

go
  •  1
  • Panagiotis Bougioukos  · 技术社区  · 4 年前

    我定义了一个自定义类型 IPAddr byte[4]

    假设一个类型的值 IP地址 {127, 2, 0, 1} .

    我需要覆盖 String() 方法,以便在窗体中打印它 127.2.0.1 [127, 2, 0, 1] .

    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)
    }
    
    1 回复  |  直到 4 年前
        1
  •  2
  •   questionerofdy    4 年前

    通过使用字符串转换,这些值将以您不期望的方式进行强制转换。您可以注意到54作为6打印,因为54的ascii值对应于“6”。

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