Golang tips/tricks

Implicit reference types

Slices, maps and channels are reference types that do not require the extra indirection of an allocation with new.

Things ain’t what they seem like
func main015() {
	m1 := make(map[int]string)
	m1[1] = "one"
	m2 := m1
	m2[2] = "two"

	for k, v := range m1 {
		fmt.Printf("%d = %s\n", k, v)
	}
}

Will output:

1 = one
2 = two

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *