string in Go is immutable

tags: learning dsa go programming

content

  • im seeing this sentence:

Because the string is immutable, it is safe for multiple strings to share the same storage

  • and in Go’s source code:
    • “Values of string type are immutable”
// string is the set of all strings of 8-bit bytes, conventionally but not
// necessarily representing UTF-8-encoded text. A string may be empty, but
// not nil. Values of string type are immutable.
type string string

what does “string is immutable” mean

string’s data structure

type string struct {
    Data *byte  // pointer to the actual bytes
    Len  int
}
  • s and t points to the same data in memory, just different starting point
  • because no code can directly modify the underlying string (hello in this case), it’s safe for s and t to share the underlying data bytes
  • and that’s why we can do s[2:3] to slice a string

up

down

reference