Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

golang 特殊字符的string怎么转成[]byte?

比如 '?' 这个字符:

    bytes := []byte{'?'}
    fmt.Print(bytes)      //输出: [129]
    
    str := "?"
    fmt.Print([]byte(str))  //输出: [194 129]

为什么转换出来的结果不一样了, 这导致我后端收到前端的数据不一致, 怎么才能保证转换出来的结果一样啊?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

呀, 又看到这个问题了, 那知乎上提问的也是同一个人了。

下面为部分分析,完整内容请参考原文

go中的字符串存储的是utf8编码的字节切片,而'?'的utf8编码就是[194 129]。

所以这个转换结果是符合预期的,如果要保证转换的结果一样就转为rune切片,rune切片保存的是字符串中每个字符的unicode


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...