Senior
What is a string in Go?
sobes.tech AI
Answer from AI
In the Go language, a string (string) is an immutable sequence of bytes, usually representing text in UTF-8 encoding. Strings in Go are a meaningful data type and are stored as a pointer to a byte array and a length.
Features of strings in Go:
- Immutability: once created, a string cannot be changed; any operations that modify the content create a new string.
- Unicode support: strings typically contain UTF-8, allowing work with multilingual text.
Example of using a string in Go:
package main
import "fmt"
func main() {
s := "Hello, world!"
fmt.Println(s)
fmt.Println(len(s)) // length in bytes
}
Here, len(s) returns the number of bytes, not the number of characters, since UTF-8 characters can occupy multiple bytes.