Convert a byte array to a string array [duplicate]

久未见 提交于 2021-01-02 18:27:11

问题


In the following method, I attempted to redefine the string method on the IPAddr type by appending bytes to an array of string

type IPAddr [4]byte

func (ip IPAddr) String() string {
    var s []string
    for _, i := range ip {
        s = append(s, i)
    }
    return fmt.Sprintf(strings.Join(s, "."))
}

cannot use i (type byte) as type string in append

playground


回答1:


Since your type is an array with a small length, so I would recommend just building the string without ranging over the elements:

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

https://play.golang.org/p/nOSj-EyXuyf

If you want to implement your solution by joining the string slice, you need to convert the bytes to their decimal representation using the strconv package:

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


来源:https://stackoverflow.com/questions/50568424/convert-a-byte-array-to-a-string-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!