将字节写入字符串构建器不会打印任何内容。

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

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(&quot;127&quot;) or sb.Write([]byte(&quot;127&quot;)). 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.

huangapple
  • 本文由 发表于 2022年8月9日 08:50:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/73285432.html
匿名

发表评论

匿名网友

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

确定