Home  >  Article  >  Backend Development  >  How do you access bytes and runes in Go strings?

How do you access bytes and runes in Go strings?

Barbara Streisand
Barbara StreisandOriginal
2024-11-19 03:39:02565browse

How do you access bytes and runes in Go strings?

Byte Accessing and Conversion in Go Strings

In Go, strings store UTF-8 encoded bytes, not characters or runes. Accessing elements of a string, denoted as str[i], returns a bytes (byte or uint8) rather than converting it to a rune.

When iterating over a string using the for ... range construct, you can access either bytes or runes. Indexing a string (e.g., str[i]) directly accesses bytes, while the loop without a conversion (for i := range str) iterates over runes.

Performance Considerations

Converting a string to a byte slice using []byte(str) does not perform an actual copy; it's optimized away. Thus, there is no performance difference between the two methods presented:

str := "large text"
for i := range str {
  // use str[i]
}
str := "large text"
str2 := []byte(str)
for _, s := range str2 {
  // use s
}

However, for maximum performance and code clarity, it's recommended to use the method that matches the intent of the code:

  • Iterate over bytes using the first method if you specifically need to access bytes.
  • Iterate over runes using the second method if you need to access characters.

Character Iteration

When iterating over rune characters in a string, it's important to note that multibyte characters, such as Unicode characters, may be represented using multiple bytes in the underlying UTF-8 encoding. The for ... range str syntax handles this automatically, returning the byte index and character (rune) value on each iteration.

Additional Resources

  • [The Go Blog: Strings, bytes, runes and characters in Go](https://blog.golang.org/strings)
  • [golang: []byte(string) vs []byte(*string)](https://go.dev/issue/22847)

The above is the detailed content of How do you access bytes and runes in Go strings?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn