github.com/aristanetworks/goarista@v0.0.0-20240514173732-cca2755bbd44/path/mapexample_test.go (about) 1 // Copyright (c) 2019 Arista Networks, Inc. 2 // Use of this source code is governed by the Apache License 2.0 3 // that can be found in the COPYING file. 4 5 package path_test 6 7 import ( 8 "fmt" 9 "sort" 10 11 "github.com/aristanetworks/goarista/path" 12 ) 13 14 func ExampleMap_Visit() { 15 var m path.Map 16 m.Set(path.New("foo", "bar", "baz"), 1) 17 m.Set(path.New("foo", path.Wildcard, "baz"), 2) 18 m.Set(path.New(path.Wildcard, "bar", "baz"), 3) 19 m.Set(path.New("foo", "bar", path.Wildcard), 4) 20 m.Set(path.New(path.Wildcard, path.Wildcard, "baz"), 5) 21 m.Set(path.New(path.Wildcard, "bar", path.Wildcard), 6) 22 m.Set(path.New("foo", path.Wildcard, path.Wildcard), 7) 23 m.Set(path.New(path.Wildcard, path.Wildcard, path.Wildcard), 8) 24 25 p := path.New("foo", "bar", "baz") 26 27 var nums []int 28 m.Visit(p, func(v interface{}) error { 29 nums = append(nums, v.(int)) 30 return nil 31 }) 32 sort.Ints(nums) 33 fmt.Println(nums) 34 35 // Output: [1 2 3 4 5 6 7 8] 36 } 37 38 func ExampleMap_VisitPrefixes() { 39 var m path.Map 40 m.Set(path.New(), 1) 41 m.Set(path.New("foo"), 2) 42 m.Set(path.New("foo", "bar"), 3) 43 m.Set(path.New("foo", "baz"), 4) 44 m.Set(path.New(path.Wildcard, "bar"), 5) 45 46 p := path.New("foo", "bar", "baz") 47 48 var nums []int 49 m.VisitPrefixes(p, func(v interface{}) error { 50 nums = append(nums, v.(int)) 51 return nil 52 }) 53 sort.Ints(nums) 54 fmt.Println(nums) 55 56 // Output: [1 2 3 5] 57 } 58 59 func ExampleMap_VisitPrefixed() { 60 var m path.Map 61 m.Set(path.New("foo"), 1) 62 m.Set(path.New("foo", "bar"), 2) 63 m.Set(path.New("foo", "bar", "baz"), 3) 64 m.Set(path.New("foo", path.Wildcard), 4) 65 66 p := path.New("foo", "bar") 67 68 var nums []int 69 m.VisitPrefixed(p, func(v interface{}) error { 70 nums = append(nums, v.(int)) 71 return nil 72 }) 73 sort.Ints(nums) 74 fmt.Println(nums) 75 76 // Ouput: [2 3 4] 77 } 78 79 func ExampleMap_Get() { 80 var m path.Map 81 m.Set(path.New("foo", "bar"), 1) 82 m.Set(path.New("baz", "qux"), nil) 83 84 a, ok := m.Get(path.New("foo", "bar")) 85 fmt.Printf("a = %v, ok = %t\n", a, ok) 86 b, ok := m.Get(path.New("foo", path.Wildcard)) 87 fmt.Printf("b = %v, ok = %t\n", b, ok) 88 c, ok := m.Get(path.New("baz", "qux")) 89 fmt.Printf("c = %v, ok = %t\n", c, ok) 90 91 // Output: 92 // a = 1, ok = true 93 // b = <nil>, ok = false 94 // c = <nil>, ok = true 95 } 96 97 func ExampleMap_Set() { 98 var m path.Map 99 p := path.New("foo", "bar") 100 101 fmt.Println(m.Set(p, 0)) 102 fmt.Println(m.Set(p, 1)) 103 104 a, ok := m.Get(p) 105 fmt.Printf("a = %v, ok = %t\n", a, ok) 106 107 // Output: 108 // true 109 // false 110 // a = 1, ok = true 111 } 112 113 func ExampleMap_Delete() { 114 var m path.Map 115 p := path.New("foo", "bar") 116 117 m.Set(p, 0) 118 119 fmt.Println(m.Delete(p)) 120 fmt.Println(m.Delete(p)) 121 122 // Output: 123 // true 124 // false 125 }