为什么Go语言使用000/s而不是字符串?

huangapple go评论88阅读模式
英文:

Why go writes 000/s instead of string?

问题

由于某些原因,Go将字符串编码为字节,我想知道这是否是Go的一个错误。请参考下面的代码:

ip, _, err := net.ParseCIDR(cidr)
if err != nil {
    log.Panicf("can't parse cidr %s, err was %v", cidr, err)
}

type Ip struct {
    Ip string
}

ips := string(ip)
j := Ip{
    Ip: ips,
}
b, err := json.Marshal(j)
if err != nil {
    log.Printf("error:", err)
}

fmt.Fprintln(w, string(b))

它输出:

{"Ip":"\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\ufffd\ufffd\ufffd\ufffd\u0007+"}

我正在从epel存储库(redhat)运行Go。我还创建了一个类似的代码片段,返回类似的结果。

[为我播放!][1]
[1]: http://play.golang.org/p/JbbbfK3whZ

英文:

For some reasons go encodes the string like bytes and I'm wondering if it's a go bug. See the code below:

ip, _, err := net.ParseCIDR(cidr)
if err!=nil{
     log.Panicf("can't parse cidr %s, err was %v", cidr, err)
}

type Ip struct{
     Ip string
}

ips := string(ip)
j:= Ip{
     Ip: ips,
}
b, err := json.Marshal(j)
if err != nil {
     log.Printf("error:", err)
}

fmt.Fprintln(w, string(b))

It prints:

{"Ip":"\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\ufffd\ufffd\ufffd\ufffd\u0007+"}

I'm running Go from epel repository ( redhat ). I also made a snippet which returns similar results.

[Play it for me!][1]
[1]: http://play.golang.org/p/JbbbfK3whZ

答案1

得分: 3

这是因为你将一系列的IP地址字节视为原始字符串。

net.ParseCIDR 返回的 net.IP 值有一个 .String() 方法,你应该调用它,而不是使用 string(ip)

尝试使用 这个 代码:

package main

import (
	"encoding/json"
	"fmt"
	"log"
	"net"
)

func main() {
	cidr := "172.162.21.84/32"

	ip, _, err := net.ParseCIDR(cidr)
	if err != nil {
		log.Panicf("无法解析CIDR %s,错误:%v", cidr, err)
	}

	type Ip struct {
		Ip string
	}

	fmt.Printf("%T: %v\n", ip, ip)

	j := Ip{
		Ip: ip.String(),
	}

	b, err := json.Marshal(j)
	if err != nil {
		log.Printf("错误:", err)
	}

	fmt.Println(string(b))
}
英文:

This happens because you are treating a sequence of IP address bytes as a raw string.

The net.IP value returned by net.ParseCIDR has a .String() method you should call, instead of doing string(ip).

Try this instead:

package main

import (
	"encoding/json"
	"fmt"
	"log"
	"net"
)

func main() {
	cidr := "172.162.21.84/32"

	ip, _, err := net.ParseCIDR(cidr)
	if err != nil {
		log.Panicf("can't parse cidr %s, err was %v", cidr, err)
	}

	type Ip struct {
		Ip string
	}

	fmt.Printf("%T: %v\n", ip, ip)

	j := Ip{
		Ip: ip.String(),
	}

	b, err := json.Marshal(j)
	if err != nil {
		log.Printf("error:", err)
	}

	fmt.Println(string(b))
}

huangapple
  • 本文由 发表于 2014年6月9日 17:53:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/24117714.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定