英文:
Writing Bytes to strings.builder prints nothing
问题
我正在学习Go语言,对于这段代码为什么没有输出结果感到不确定。
package main
import (
"strings"
)
func main(){
var sb strings.Builder
sb.WriteByte(byte(127))
println(sb.String())
}
我期望它输出 127。
英文:
I am learning go and am unsure why this piece of code prints nothing
package main
import (
"strings"
)
func main(){
var sb strings.Builder
sb.WriteByte(byte(127))
println(sb.String())
}
I would expect it to print 127
答案1
得分: 2
您正在将一个字节追加到字符串的缓冲区中,而不是字符"127"。
由于Go字符串是UTF-8编码的,任何小于等于127的数字都将与ASCII中的相应数字表示相同的字符。您可以在此ASCII表中看到,127代表的是"delete"字符。由于"delete"是一个不可打印的字符,println
不会输出任何内容。
这里有一个示例,展示了从您的问题中进行相同操作的示例,但使用了可打印的字符。90代表的是字符"Z"。您可以看到它确实打印出了Z。
如果您想追加字符"127",您可以使用sb.WriteString("127")
或sb.Write([]byte("127"))
。如果您想追加字节的字符串表示形式,您可以考虑使用fmt.Sprintf
。
注意:我对字符编码不是专家,如果本回答中的术语有误,请谅解。
英文:
You are appending a byte to the string's buffer, not the characters "127".
Since Go strings are UTF-8, any number <=127 will be the same character as that number in ASCII. As you can see in this ASCII chart, 127 will get you the "delete" character. Since "delete" is a non-printable character, println
doesn't output anything.
Here's an example of doing the same thing from your question, but using a printable character. 90 for "Z". You can see that it does print out Z.
If you want to append the characters "127" you can use sb.WriteString("127")
or sb.Write([]byte("127"))
. If you want to append the string representation of a byte, you might want to look at using fmt.Sprintf
.
Note: I'm not an expert on character encoding so apologies if the terminology in this answer is incorrect.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论