Skip to content

Instantly share code, notes, and snippets.

@maiah
Created October 2, 2015 09:03
Show Gist options
  • Save maiah/04f71df28226fe2bb079 to your computer and use it in GitHub Desktop.
Save maiah/04f71df28226fe2bb079 to your computer and use it in GitHub Desktop.
Copy Method for Immutable slices and maps
package main
import "fmt"
type nums []int
func (n nums) copy() []int {
dest := make(nums, len(n))
copy(dest, n)
return dest
}
type codes map[string]int
func (c codes) copy() map[string]int {
dest := make(codes)
for k, v := range c {
dest[k] = v
}
return dest
}
func main() {
// slice
x := nums{2, 5}
fmt.Println(x)
// try changing
change(x.copy())
// is changed?
fmt.Println(x)
// map
y := make(codes)
y["red"] = 1
y["blue"] = 2
fmt.Println(y)
// try changing
changeMap(y.copy())
// is changed?
fmt.Println(y)
}
func change(src []int) {
src[0] = 3
fmt.Println(src)
}
func changeMap(src map[string]int) {
src["red"] = 3
fmt.Println(src)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment