Immutability of string in Golang

104 阅读1分钟

String in Golang has immutability, which means modifying a string value will allocate a new space for the new value, not occupying the original space and updating its memory. Let's see an example,

package main

import "fmt"

type printer interface {
	print()
}

type user struct {
	name string
}

func (u user) print() {
	fmt.Println(u.name)
}

func main() {
	u := user{"tom"}
	s := []printer{
		u,
		&u,
	}
	u.name = "new"
	for _, item := range s {
		item.print()
	}
}

and the output,

tom
new

u.name is assigned a new value, the index zero of s is value type, it's a copy of original u, with name pointing to tom, when u.name is modified, this copy will not change, the original u has been modified to new.