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:
When we reassign a string in a program, such as this:
s := "Hello World"
s = "Hello AlwaysBeta"
The underlying storage becomes like this:
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
- Go Language Tutorial – Introduction (1)
- Go Language Tutorial – Language Structure (2)
- Go Language Tutorial – Language Structure (3)
- Go Language Tutorial – Data Types (4)
- Go Language Tutorial – Language Variables (5)
- Go Language Tutorial – GO Language Constants (6)
- Go Language Tutorial – GO Language Operators (7)
- Go Language Tutorial – GO Conditions and Loop Statements (8)
- Go Language Tutorial – GO Language Functions (9)
- Go Language Tutorial – GO Language Variable Scope (10)
- Go Language Tutorial – GO Language Array (11)
- Go Language Tutorial – GO Language Pointer (12)
- Go Language Tutorial – GO Language Structure (13)
- Go Language Tutorial – GO Language Slice (Slice) (14)
- Go Language Tutorial – Go Language Range (Range) (15)
- Go Language Tutorial – Go Language Map (Collection) (16)
- Go Language Tutorial – Go Language Recursive Function (17)
- Go Language Tutorial – Go Language Type Conversion (18)
- Go Language Tutorial – Go Language Interface (19)
- Go Language Tutorial – Go Error Handling (20)
- Go Language Tutorial – Go Concurrency (21)