Skip to content

Instantly share code, notes, and snippets.

@yehudamakarov
Created June 17, 2020 16:43
Show Gist options
  • Save yehudamakarov/be578892353289c610b34a8a41e0d1c4 to your computer and use it in GitHub Desktop.
Save yehudamakarov/be578892353289c610b34a8a41e0d1c4 to your computer and use it in GitHub Desktop.
[Go Concepts]
package main
import "fmt"
func main() {
slc := []int{1,2}
adjustSlice(slc)
fmt.Println(slc)
map1 := make(map[int]int)
adjustMap(map1)
fmt.Println(map1)
sliceOfMaps := []map[int]int{ map[int]int{1: 10, 2: 20}, map[int]int{3: 30, 4: 40} }
for _, val := range sliceOfMaps {
// val here is a COPY of the return value of map[int]int{1: 10, 2: 20} which is a pointer.
// setting to it works because go dereferences the copied map pointer automatically
//
val[5] = 50
// vs
//
// not sure of the way to take a pointer to a map (let's say the map is nil) and initialize the map through the pointer
// the original question was trying to do this and yes, all you are doing is taking the copy of the pointer to the map (val)
// and assigning a new pointer to a new map to it.
//
// val = make(map[int]int)
// val[5] = 50
}
fmt.Println(sliceOfMaps)
}
func adjustSlice(slc []int) {
// slc is a copied slice header and indexing into a slice header finds the underlying
// array and allows assignment
//
slc[0] = 12345
// vs
//
// slc = []int { 12345, 2}
//
// takes your slice header which is a copy and assigns a new slice header to it.
// now the local variable is not the original slice header, rather it is a new one.
// so the following assignment has no affect on the source slice header
}
func adjustMap(map1 map[int]int) {
// map1 = map[int]int{1:10}
//
// takes the pointer to the map (which is just a copy) and overrides it with a new pointer to a new map
// vs
//
map1[1] = 10
//
// takes the pointer to the map (which is just a copy) and dereferences it automatically to set an item in it
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment