duankang8114 2018-10-02 10:09
浏览 96

在磁盘上存储结构树

I have the following struct:

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

To add some data, I do the following:

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"})

How can I efficiently store this struct tree on disk? I'm looking for something which can be used without a server (like SQLite). I would like to be able to search for Id 2 or 3, returning the entire struct with the Id 2 or 3, respectively. Also, I would like to be able to update a single struct, f.e. the one with Id 2.

Also, would it be better to use a map, using Id as the map's key?

  • 写回答

1条回答 默认 最新

  • dpd46554 2018-10-02 13:37
    关注

    Use the encoding/gob put the binary data in a file or get it out again

    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
    ", posts)
    
        path := "post.gob"
    
        // write
        out, err1 := os.Create(path)
        if err1 != nil {
            fmt.Printf("File write error: %v
    ", 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
    ", err2)
            os.Exit(1)
        }
        r := bufio.NewReader(in)
        dec := gob.NewDecoder(r)
        dec.Decode(&b)
    
        fmt.Printf("%v
    ", b)
    
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序