当前位置: 移动技术网 > IT编程>脚本编程>Go语言 > Go Web:数据存储(1)——内存存储

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

2018年12月03日  | 移动技术网IT编程  | 我要评论

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

内存存储

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

例如,要存储博客文章。

每篇博客文章都有文章id、文章内容以及文章作者。假设它是一个struct结构:

type post struct {
    id      int
    content string
    author  string
}

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

var postbyid map[int]*post

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

如果想要通过author来检索文章,则还可以使用一个map来存储这个作者下的所有文章。因为一个作者可以有多篇文章,所以map的value应该是一个容器,比如slice。

var postbyauthor map[string][]*post

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

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

现在假设就前面定义的两种存储方式:postbyid和postbyauthor,定义提交文章的函数:

func store(post *post) {
    postbyid[post.id] = post
    postbyauthor[post.author] = append(postbyautor[post.autor], post)
}

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

文章存储到上面两种容器中后,就可以从任意一种容器中检索文章。因为存储时是使用指针类型存储的,所以无论从哪一种容器中检索得到的文章,和另一种方式检索得到的是相同的文章。

例如:

// 按文章id检索文章并输出文章的content
fmt.println(postbyid[1])
fmt.println(postbyid[2])

// 按作者检索文章并输出文章的content
for _, post := range postbyauthor["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)
    }
}

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网