Go 的 string 是否线程安全
stringstringstringstring
string
func TestModifyString(t *testing.T) {
	var s string = "abc"
	s[0] = '0' // Cannot assign to s[0]
}

执行这个测试得到的结果:

cannot assign to s[0] (value of type byte)
string
func TestString2(t *testing.T) {
	a := "hello"
	a = "world"
	fmt.Println(a)
}

执行这个测试得到的结果:

world
string
stringstructstrlen
runtime/string.go
type stringStruct struct {
    str unsafe.Pointer
    len int
}
string
func TestString(t *testing.T) {
	ch := make(chan string)
	a := "1"
	go func() {
		i := 0
		for {
			if i%2 == 0 {
				a = "1"
			} else {
				a = "22"
			}
			time.Sleep(time.Millisecond * 1) // 阻止编译器优化
			i++
		}
	}()

	go func() {
		for {
			b := a
			if b != "1" && b != "22" {
				ch <- b
			}
		}
	}()

	for i := 0; i < 10; i++ {
		fmt.Println("Got string: ", <-ch)
	}
}

执行这个测试得到的结果:

Got string:  2
Got string:  2
Got string:  15
Got string:  2
Got string:  2
Got string:  15
Got string:  15
Got string:  15
Got string:  2
Got string:  2
len22len1
stringinterfaceatomic

参考

https://stackoverflow.com/questions/51249918/immutability-of-string-and-concurrency