go - 将字节数组转换为字符串数组

标签 go

<分区>

在下面的方法中,我试图通过将字节附加到字符串数组来重新定义 IPAddr 类型的字符串方法

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

最佳答案

由于您的类型是一个长度较小的数组,所以我建议只构建字符串而不遍历元素:

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

如果您想通过加入字符串 slice 来实现您的解决方案,您需要使用 strconv 包将字节转换为它们的十进制表示:

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, ".")
}

关于go - 将字节数组转换为字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50568424/

相关文章:

postgresql - Golang Postgres 如何将表转储为 JSON

戈朗 : Make function and third param

go - 我的目录 "expects"中的代码特定导入是什么意思?

go - 如何从 map 界面获取/设置值?

json - 如何在 Go 中使用非必需的 JSON 参数?

git - 如何将 go.mod 中的 Go 模块依赖项指向 repo 中的最新提交?

go - 无法将变量分配给 for 循环中的匿名函数

unit-testing - Google App Engine 数据存储 - 测试查询失败

json - 在golang中解析没有索引名称的json

javascript - 更新变量时动态刷新模板的一部分golang