在磁盘上存储结构树

时间:2018-10-02 10:09:13

标签: go struct

我具有以下结构:

myFile.name;
myFile.accepted;

要添加一些数据,请执行以下操作:

type Post struct {
  Id    int
  Name  string
  Text  string
  Posts []Post
}

如何有效地将此结构树存储在磁盘上?我正在寻找无需服务器即可使用的东西(例如SQLite)。我希望能够搜索var posts []Post posts = append(posts, Post{Id: 0, Name: "a", Text: "b"}) posts[0].Posts = append(posts[0].Posts, Post{Id: 1, Name: "c", Text: "d"}) posts = append(posts, Post{Id: 2, Name: "e", Text: "f"}) posts[0].Posts = append(posts[0].Posts, Post{Id: 3, Name: "h", Text: "d"}) 2或3,分别返回带有Id 2或3的整个结构。另外,我希望能够更新单个结构,例如带有Id 2的那个。

还有,使用地图,以Id作为地图的键会更好吗?

1 个答案:

答案 0 :(得分:1)

使用编码/目标将二进制数据放入文件中或再次将其取出

import (
    "bufio"
    "encoding/gob"
    "fmt"
    "os"
)

type Post struct {
    Id    int
    Name  string
    Text  string
    Posts []Post
}

func main() {

    var posts []Post

    posts = append(posts, Post{Id: 0, Name: "a", Text: "b"})
    posts[0].Posts = append(posts[0].Posts, Post{Id: 1, Name: "c", Text: "d"})

    posts = append(posts, Post{Id: 2, Name: "e", Text: "f"})
    posts[0].Posts = append(posts[0].Posts, Post{Id: 3, Name: "h", Text: "d"})
    fmt.Printf("%v\n", posts)

    path := "post.gob"

    // write
    out, err1 := os.Create(path)
    if err1 != nil {
        fmt.Printf("File write error: %v\n", err1)
        os.Exit(1)
    }
    w := bufio.NewWriter(out)
    enc := gob.NewEncoder(w)
    enc.Encode(posts)
    w.Flush()
    out.Close()

    // read
    b := make([]Post, 10)
    in, err2 := os.Open(path)
    if err2 != nil {
        fmt.Printf("File read error: %v\n", err2)
        os.Exit(1)
    }
    r := bufio.NewReader(in)
    dec := gob.NewDecoder(r)
    dec.Decode(&b)

    fmt.Printf("%v\n", b)

}