Strings

Learn about strings and byte arrays in Go.

Strings in Go

Internally a Go string is defined like this:

Press + to interact
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:

Press + to interact
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 ...