Search⌘ K
AI Features

Strings

Explore how strings work in Go, including their immutable nature, zero value, and internal representation. Learn best practices for string manipulation and when to use strings.Builder for efficient memory management.

Strings in Go

Internally a Go string is defined like this:

Go (1.16.5)
type StringHeader struct {
Data uintptr
Len int
}

A string itself is a value type, it has a pointer to a byte array and a fixed length. Zero byte in a string doesn’t mark the end of the string as it does in C. There can be any data inside of a string. Usually that data is encoded as a UTF-8 string, but it doesn’t have to be.

Strings can’t be nil

Strings are never nil in Go. The default value of a string is an empty string, not nil:

Go (1.16.5)
package main
import "fmt"
func main() {
var s string
fmt.Println(s == "") // true
s = nil // error: cannot use nil as type string in assignment
}

Strings are immutable (sort of)

Go does not ...