Strings
A string is an immutable sequence of bytes, usually UTF-8 text. Assignment copies a header (pointer and length). Indexing yields a byte. Ranging yields runes.
Detailed Explanation
"shop" is a string. So is a slice of bytes you converted with string(buf). The language does not store a character type in the string; it stores bytes. UTF-8 is the convention, not a runtime flag. A string can hold invalid UTF-8. len(s) is the byte count.
Immutable. There is no s[0] = 'A'. Concatenation (s + t) and slicing (s[1:4]) produce new headers. Slicing a string does not copy the bytes; the new string points into the same array. Converting []byte(s) copies, so later writes to the slice cannot change s.
Building text. Repeated s += chunk in a loop copies more each time. Use strings.Builder or bytes.Buffer, then String(). fmt.Sprintf is fine for a handful of pieces. strings.Join is the right tool for a slice of parts with a separator.
Comparison and maps. Strings compare lexicographically by bytes. They are comparable, so they are the usual map key. Two strings are equal when they have the same bytes, even if they point at different arrays.
Empty, not nil. A string cannot be nil. var s string is "". A *string can be nil and is how some APIs mean "omit this optional text."
What it costs. A string header is two words. The bytes live on the heap if they escape, or in the binary if they are constants. Converting large []byte to string copies. In a hot path that only needs to look at bytes, keep []byte and use bytes instead of strings. The two packages mirror each other: strings.Contains vs bytes.Contains.
Code Examples
package main
import (
"fmt"
"strings"
)
func main() {
s := "Go€"
fmt.Println(len(s), s[0]) // 5 71 — bytes
fmt.Println(s[0:2]) // Go
var b strings.Builder
b.WriteString("hello ")
b.WriteString("shop")
fmt.Println(b.String())
}func join(parts []string) string {
return strings.Join(parts, ",")
}func asBytes(s string) []byte {
return []byte(s) // copy
}Common Gotchas
`len(s)` is bytes, not runes
`"€"` has length 3. Use `utf8.RuneCountInString` or range when you mean characters.
`s +=` in a loop allocates repeatedly
use `strings.Builder`.
`s[i]` is a `byte`, not a `rune`
a multi-byte character will be a torn index if you walk by `i++` instead of `range`.
`string(65)` is `"A"`, not `"65"`
use `strconv.Itoa` for decimals.