[Golang] Golang Advanced Series Tutorials--Why are Go language strings immutable?

Article directory

foreword

Recently, a reader left a message saying that in the process of writing code, strings are usually modified, but it is said on the Internet that strings in Go language are immutable. Why is this?

This question itself is not difficult, but it is indeed easy to cause confusion for novices, so I will answer it today.

First look at its underlying structure:

type stringStruct struct {
    
    
    str unsafe.Pointer
    len int
}

It is very similar to the slice structure, except that there is one less cap field to indicate the capacity.

  • str: A pointer to a []byte type
  • len: the length of the string

So, when we define a string:

s := "Hello World"

Then it is stored in memory like this:
insert image description here

When we reassign a string in a program, such as this:

s := "Hello World"

s = "Hello AlwaysBeta"

The underlying storage becomes like this:
insert image description here

Go actually re-creates a []byte{} slice, and then makes the pointer point to the new address.

More directly, we directly modify a single character in the string, such as:

s := "Hello World"
s[0] = 'h'

If you do this, you will directly report an error:

cannot assign to s[0] (strings are immutable)

If you must do this, you need to convert the string to []byte type, and then convert it back to string type after modification:

s := "Hello World"
sBytes := []byte(s)
sBytes[0] = 'h'
s = string(sBytes)

that's it.

recommended reading

Guess you like

Origin blog.csdn.net/u011397981/article/details/132011136