golang ctrie demo

下载ctrie:

go get -t github.com/Workiva/go-datastructures/trie/ctrie

测试demo1:

package main

import (
    "fmt"
    "github.com/Workiva/go-datastructures/trie/ctrie"
    "strconv"
)

type dataStruct struct {
    id int64
    x  int64
    y  int64
    a  string
    b  string
}

func main() {
    rect1 := &dataStruct{1, 1, 2, "sss", "rrr"}
    rect2 := &dataStruct{2, 2, 4, "aaa", "xxx"}
    rect3 := &dataStruct{3, 3, 5, "bbb", "yyy"}

    ctrie := ctrie.New(nil)
    key1 := []byte(strconv.Itoa(int(rect1.id)))
    ctrie.Insert(key1, rect1)

    key2 := []byte(strconv.Itoa(int(rect2.id)))
    ctrie.Insert(key2, rect2)

    key3 := []byte(strconv.Itoa(int(rect3.id)))
    ctrie.Insert(key3, rect3)

    key := []byte(strconv.Itoa(int(rect3.id)))

    val, exists := ctrie.Lookup(key)
    if exists {
        data := val.(*dataStruct)
        fmt.Println(data.a)
        ctrie.Remove(key)
    }

    val, exists = ctrie.Lookup(key)
    if !exists {
        fmt.Println("Not find")
    }

    return
}

运行结果:

[root@wangjq ctrie]# go run main.go 
bbb
Not find

 

测试demo2:

package main

import (
    "fmt"
    "github.com/Workiva/go-datastructures/trie/ctrie"
    "bytes"
)

type dataStruct struct {
    id int64
    x  int64
    y  int64
    a  string
    b  string
}

func main() {
    rect := &dataStruct{1, 1, 2, "sss", "rrr"}

    buf := &bytes.Buffer{}
    buf.WriteString("123456")
    key := buf.Bytes()

    ctrie := ctrie.New(nil)
    ctrie.Insert(key, rect)

    buf_tmp := &bytes.Buffer{}
    buf_tmp.WriteString("123456")
    key_tmp := buf_tmp.Bytes()

    val, exists := ctrie.Lookup(key_tmp)
    if exists {
        data := val.(*dataStruct)
        fmt.Println(data.a)
        ctrie.Remove(key_tmp)
    }

    val, exists = ctrie.Lookup(key_tmp)
    if !exists {
        fmt.Println("Not find")
    }

    return
}

运行结果:

[root@ctrie]# go run demo.go 
sss
Not find

 

posted @ 2019-10-29 10:13  salami_china  阅读(287)  评论(0编辑  收藏  举报