Sobes.tech
Senior

What does the string data type in Go look like?

sobes.tech AI

Answer from AI

In Go, the string type represents an immutable sequence of bytes, typically used to store text data in UTF-8 encoding. Strings in Go are byte slices with a fixed length, where each element is a byte.

Features:

  • Strings are immutable: you cannot change individual bytes within a string.
  • You can easily get the length of a string in bytes using len().
  • To work with Unicode characters (runes), the rune type is used.

Example:

s := "Привет"
fmt.Println(len(s)) // Prints the number of bytes, not characters
runes := []rune(s)
fmt.Println(len(runes)) // Prints the number of characters

Thus, string in Go is a convenient and efficient type for working with text, but it is important to remember the difference between bytes and Unicode characters.