Sobes.tech
Junior — Middle

Explain the concept of string type in the Go language and its main features.

sobes.tech AI

Answer from AI

In the Go language, the string (string) type represents an immutable sequence of bytes, typically used to store text in UTF-8 encoding.

Main features of strings in Go:

  • Immutability: Once created, a string cannot be changed. Any operations that modify a string create a new string.
  • UTF-8 encoding: Strings are stored in UTF-8, allowing for multilingual text processing.
  • Byte access: Indexing a string returns a byte, not a character (rune). To work with characters, the rune type is used.
  • Support for slices: Substrings can be obtained using slices, e.g., s[0:5].

Example of working with strings and runes:

s := "Привет"
fmt.Println(len(s)) // number of bytes
for i, r := range s {
    fmt.Printf("%d: %c\n", i, r) // output byte index and character
}

Thus, strings in Go are a convenient and efficient way to work with text, but they require understanding the difference between bytes and characters.