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