Home > database >  Writing Bytes to strings.builder prints nothing
Writing Bytes to strings.builder prints nothing

Time:08-09

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

CodePudding user response:

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.

  • Related