Skip to content

Instantly share code, notes, and snippets.

@xtrcode
Created February 21, 2019 16:13
Show Gist options
  • Save xtrcode/8fdffd4a9a036517fa217046f40c59c4 to your computer and use it in GitHub Desktop.
Save xtrcode/8fdffd4a9a036517fa217046f40c59c4 to your computer and use it in GitHub Desktop.
Go Create Copy Of sync.Map
func CopySyncMap(m sync.Map) sync.Map {
var cp sync.Map
m.Range(func(k, v interface{}) bool {
vm, ok := v.(sync.Map)
if ok {
cp.Store(k, CopySyncMap(vm))
} else {
cp.Store(k, v)
}
return true
})
return cp
}
@xtrcode
Copy link
Author

xtrcode commented Feb 21, 2019

Usage:

package main

import (
	"fmt"
	"sync"
)

func print(m sync.Map) {
	m.Range(func(key, value interface{}) bool {
		fmt.Println(key, value)

		return true
	})
}

func CopySyncMap(m sync.Map) sync.Map {
	var cp sync.Map

	m.Range(func(k, v interface{}) bool {
		vm, ok := v.(sync.Map)
		if ok {
			cp.Store(k, CopySyncMap(vm))
		} else {
			cp.Store(k, v)
		}

		return true
	})

	return cp
}

func main() {
	m, n := sync.Map{}, sync.Map{}

	n.Store(1337, []float64{.5, .2, .99})

	m.Store(0, []int{1, 2, 3, 4})
	m.Store(1, []int{5, 6, 7, 8})
	m.Store(2, n)

	n = CopySyncMap(m)

	fmt.Println("Original:")
	print(m)

	fmt.Println("Copy:")
	print(n)

	fmt.Println("\nDelete from original")
	m.Delete(0)

	fmt.Println("Original:")
	print(m)

	fmt.Println("Copy:")
	print(n)

	fmt.Println("\nModify copy")
	v, _ := n.Load(2)
	v2 := v.(sync.Map)
	v2.Delete(1337)

	fmt.Println("Original:")
	print(m)

	fmt.Println("Copy:")
	print(n)
}

Output:

~ go run test.go
Original:
1 [5 6 7 8]
2 {{0 0} {{map[] true}} map[1337:0xc42000c028] 0}
0 [1 2 3 4]
Copy:
2 {{0 0} {{map[] true}} map[1337:0xc42000c058] 0}
0 [1 2 3 4]
1 [5 6 7 8]

Delete from original
Original:
2 {{0 0} {{map[] true}} map[1337:0xc42000c028] 0}
1 [5 6 7 8]
Copy:
0 [1 2 3 4]
1 [5 6 7 8]
2 {{0 0} {{map[] true}} map[1337:0xc42000c058] 0}

Modify copy
Original:
1 [5 6 7 8]
2 {{0 0} {{map[] true}} map[1337:0xc42000c028] 0}
Copy:
0 [1 2 3 4]
1 [5 6 7 8]
2 {{0 0} {{map[] true}} map[] 0}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment