Go Web:数据存储(1)——内存存储

数据能够存储在内存中、文件中、按二进制序列化存储的文件中、数据库中等。html

内存存储

将数据存储到内存中。此处所指的内存是指应用程序自身的内存空间(如slice、array、map、struct、队列、树等等容器),而不是外部的内存数据库(如redis)。linux

例如,要存储博客文章。redis

每篇博客文章都有文章ID、文章内容以及文章做者(关于博客类文章,通常还有浏览量、点赞数量、评论、文章发表时间、文章是否置顶、标签、是否转载等等属性)。假设它是一个struct结构:docker

type Post struct {
    Id      int
    Content string
    Author  string
}

为了在内存中存储每一篇Post,能够考虑将每篇Post放进一个slice,也能够放进map。由于id或author或content和文章之间有映射关系,使用map显然更好一些。shell

var PostById map[int]*Post

这样就能经过Id来检索对应的文章,注意上面map的value是指针类型的,不建议使用值类型的,这样会产生副本。数据库

若是想要经过Author来检索文章,则还能够使用一个map来存储这个做者下的全部文章。由于一个做者能够有多篇文章,因此map的value应该是一个容器,好比slice。app

var PostsByAuthor map[string][]*Post

还能够关键字来检索Content从而找出关键字近似的文章,也就是搜索引擎类型的检索方式。这个比较复杂一些。函数

还有一些文章设置了标签关键字,好比linux类的文章,docker标签的文章,shell标签的文章等。为了能够使用标签检索文章,还须要建立一个按照标签方式进行存储文章的map容器。关于标签的存储方式,此处略过。post

如今假设就前面定义的两种存储方式:PostById和PostsByAuthor,定义提交文章的函数:搜索引擎

func store(post *Post) {
    PostById[post.Id] = post
    PostsByAuthor[post.Author] = append(PostByAutor[post.Autor], post)
}

注意,上面store()函数的参数是指针类型的。

文章存储到上面两种容器中后,就能够从任意一种容器中检索文章。由于存储时是使用指针类型存储的,因此不管从哪种容器中检索获得的文章,和另外一种方式检索获得的是相同的文章。

例如:

// 按文章Id检索文章并输出文章的Content
fmt.Println(PostById[1])
fmt.Println(PostById[2])

// 按做者检索文章并输出文章的Content
for _, post := range PostsByAuthor["userA"]{
    fmt.Println(post)
}

下面是完整的代码:

package main

import (
    "fmt"
)

type Post struct {
    Id      int
    Content string
    Author  string
}

// 用于存储的两个内存容器
var PostById map[int]*Post
var PostsByAuthor map[string][]*Post

// 存储数据
func store(post *Post) {
    PostById[post.Id] = post
    PostsByAuthor[post.Author] = append(PostsByAuthor[post.Author], post)
}

func main() {
    PostById = make(map[int]*Post)
    PostsByAuthor = make(map[string][]*Post)
    post1 := &Post{Id: 1, Content: "Hello 1", Author: "userA"}
    post2 := &Post{Id: 2, Content: "Hello 2", Author: "userB"}
    post3 := &Post{Id: 3, Content: "Hello 3", Author: "userC"}
    post4 := &Post{Id: 4, Content: "Hello 4", Author: "userA"}
    store(post1)
    store(post2)
    store(post3)
    store(post4)
    fmt.Println(PostById[1])
    fmt.Println(PostById[2])
    for _, post := range PostsByAuthor["userA"] {
        fmt.Println(post)
    }
    for _, post := range PostsByAuthor["userC"] {
        fmt.Println(post)
    }
}

执行结果:

&{1 Hello 1 userA}
&{2 Hello 2 userB}
&{1 Hello 1 userA}
&{4 Hello 4 userA}
&{3 Hello 3 userC}
相关文章
相关标签/搜索