Create a gist now

Instantly share code, notes, and snippets.

@dc0d /main.go
Last active May 1, 2017

What would you like to do?
Go Reference Types
package main
import (
"fmt"
"sync"
)
/*
output:
map[0:110]
map[0:66]
map[0:66 1:1]
map[10:10]
[110]
[66]
[66 1]
[10]
110 66
10
*/
func main() {
labMaps()
labSlices()
labChans()
wg.Wait()
}
func mutateMap(m map[int]int) {
m[0] = 66
}
func remakeMap(m *map[int]int) {
*m = make(map[int]int)
(*m)[10] = 10
}
func labMaps() {
m := make(map[int]int)
m[0] = 110
fmt.Println(m) // map[0:110]
mutateMap(m)
fmt.Println(m) // map[0:66]
m[1] = 1
fmt.Println(m) // map[1:1 0:66]
remakeMap(&m)
fmt.Println(m) // map[10:10]
}
func mutateSlice(s []int) {
s[0] = 66
}
func remakeSlice(s *[]int) {
*s = make([]int, 1)
(*s)[0] = 10
}
func labSlices() {
s := make([]int, 1)
s[0] = 110
fmt.Println(s) // [110]
mutateSlice(s)
fmt.Println(s) // [66]
s = append(s, 1)
fmt.Println(s) // [66 1]
remakeSlice(&s)
fmt.Println(s) // [10]
}
func mutateChan(s chan int) {
s <- 66
}
func remakeChan(s *chan int) {
*s = make(chan int, 1)
(*s) <- 10
}
var (
wg sync.WaitGroup
)
func labChans() {
c := make(chan int, 1)
wg.Add(1)
go func() {
defer wg.Done()
for v := range c {
fmt.Print(v, " ") // 110 66
}
fmt.Println()
}()
c <- 110
mutateChan(c)
close(c)
wg.Wait()
remakeChan(&c)
close(c)
wg.Add(1)
go func() {
defer wg.Done()
for v := range c {
fmt.Print(v, " ") // 10
}
fmt.Println()
}()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment