github.com/go-ego/cedar@v0.10.2/example_test.go (about) 1 package cedar_test 2 3 import ( 4 "fmt" 5 6 "github.com/go-ego/cedar" 7 ) 8 9 var trie *cedar.Cedar 10 11 func Example() { 12 trie = cedar.New() 13 14 // Insert key-value pairs. 15 // The order of insertion is not important. 16 trie.Insert([]byte("How many"), 0) 17 trie.Insert([]byte("How many loved"), 1) 18 trie.Insert([]byte("How many loved your moments"), 2) 19 trie.Insert([]byte("How many loved your moments of glad grace"), 3) 20 trie.Insert([]byte("姑苏"), 4) 21 trie.Insert([]byte("姑苏城外"), 5) 22 trie.Insert([]byte("姑苏城外寒山寺"), 6) 23 24 // Get the associated value of a key directly. 25 value, _ := trie.Get([]byte("How many loved your moments of glad grace")) 26 fmt.Println(value) 27 28 // Or, use `jump` to get the id of the trie node fist, 29 id, _ := trie.Jump([]byte("How many loved your moments"), 0) 30 // then get the key and the value. 31 key, _ := trie.Key(id) 32 value, _ = trie.Value(id) 33 fmt.Printf("%d\t%s:%v\n", id, key, value) 34 35 // Output: 36 // 3 37 // 281 How many loved your moments:2 38 } 39 40 func Example_prefixMatch() { 41 fmt.Println("id\tkey:value") 42 for _, id := range trie.PrefixMatch( 43 []byte("How many loved your moments of glad grace"), 0) { 44 key, _ := trie.Key(id) 45 value, _ := trie.Value(id) 46 fmt.Printf("%d\t%s:%v\n", id, key, value) 47 } 48 // Output: 49 // id key:value 50 // 262 How many:0 51 // 268 How many loved:1 52 // 281 How many loved your moments:2 53 // 296 How many loved your moments of glad grace:3 54 } 55 56 func Example_prefixPredict() { 57 fmt.Println("id\tkey:value") 58 for _, id := range trie.PrefixPredict([]byte("姑苏"), 0) { 59 key, _ := trie.Key(id) 60 value, _ := trie.Value(id) 61 fmt.Printf("%d\t%s:%v\n", id, key, value) 62 } 63 // Output: 64 // id key:value 65 // 303 姑苏:4 66 // 309 姑苏城外:5 67 // 318 姑苏城外寒山寺:6 68 } 69 70 func Example_saveAndLoad() { 71 trie.SaveToFile("cedar.gob", "gob") 72 trie.SaveToFile("cedar.json", "json") 73 74 trie.LoadFromFile("cedar.gob", "gob") 75 trie.LoadFromFile("cedar.json", "json") 76 }