繁体   English   中英

如何在 Go[lang] 中将字节转换为字符串

[英]How To Convert Bytes Into Strings In Go[lang]

我是 Go 的新手并尝试进行纵梁练习,但我无法在 Go 中将bytes转换为string 我查看并找到了一个解决方案string(i[:])但这不起作用。 下面是我的完整代码

package main

import (
    "fmt"
)

type IPAddr [4]byte

func (i IPAddr) String() string {
    // not sure how to turn bytes into string ?
   // expected result: from {127, 0, 0, 1} -> 127.0.0.1
    return string(i[:])
}

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

预期的结果是

loopback: 127.0.0.1
googleDNS: 8.8.8.8

任何帮助将非常感激。

干杯,DD。

将 4 字节数组转换为“点四边形”的“正确”方法would be to use the in-built网络 package:

package main

import (
  "fmt"
  "net"
)

func main() {
  octets     := []byte{123, 45, 67, 89}
  ip         := net.IP(octets)
  dottedQuad := ip.To4().String()

  fmt.Printf("%v is %s\n", octets, dottedQuad)

}

String()更改为此

func (i IPAddr) String() string {
    // return fmt.Sprintf("%d.%d.%d.%d", i[0], i[1], i[2], i[3])
    var res string
    for _, v := range i {
        res += strconv.Itoa(int(v)) + "."
    }
    return res[:len(res)-1]
}

You can't just output the UTF-8 encoded value as the string the 127 take as the UTF-8 value not the string so you should change the integer to the string first. 而在 Golang integer 类型不能直接转换为字符串没有 function 像strconv.Itoa()fmt.Sprintf('%d', int)

你的代码可以像

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM