我有这段代码,其中我使用[]byte
将字符串转换为json.Marshal
slice 。打印时,为什么fmt.Println()
将数字写入stdout而os.Stdout.Write
写入字符串。
我的问题是fmt.Println
如何解析[]byte
。
package main
import (
"encoding/json"
"fmt"
"os"
)
func main(){
str := "My string"
dat,_:= json.Marshal(str)
fmt.Println(dat)
os.Stdout.Write(dat)
}
我得到以下输出[34 77 121 32 115 116 114 105 110 103 34]
"My string"
最佳答案
fmt.Println
为 byte slice 生成友好格式。由于 byte slice 完全可以包含任何内容(而不仅仅是可打印字符),因此它显示了各个字节值。按照docs: byte slice 打印为:
the uninterpreted bytes of the string or slice
另一方面,
os.Stdout.Write
将 byte slice 写入标准输出。因为它们是可打印字符,所以您的终端可以正确呈现它们。尝试使用不可打印的字符,
fmt.Println
行为的原因将变得清楚:func main() {
dat := []byte{0, 1, 2, 3, 4}
fmt.Println(dat)
os.Stdout.Write(dat)
}
输出:[0 1 2 3 4]
XXXX // four non-printable character placeholders (based on your terminal)
至于json,它的输出是一个 byte slice ,因为这是传递给编写器(网络,磁盘,存储等)的最有用的格式。
关于go - fmt.Println与os.Stdout.Write,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63490480/