Working with Strings
String is one of the fundamental data types in Go.
Go uses immutable UTF-8-encoded strings. This might be confusing for a new developer; after all, this works:
x:="Hello" x+=" World" fmt.Println(x) // Prints Hello World
Didn’t we just change x
? Yes, we did. What is immutable here are the "Hello"
and " World"
strings. So, the string itself is immutable, but the string variable, x
, is mutable. To modify string variables, you create slices of bytes or runes (which are mutable), work with them, and then convert them back to a string.
UTF-8 is the most common encoding used for web and internet technologies. This means that any time you deal with text in a Go program, you deal with UTF-8 strings. If you have to process data in a different encoding, you first translate it to UTF-8, process it, and encode it back to its original encoding.
UTF-8 is a variable-length encoding that uses one to four bytes for each...