经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » Go语言 » 查看文章
Go Web:数据存储(1)——内存存储
来源:cnblogs  作者:骏马金龙  时间:2018/12/3 10:10:38  对本文有异议

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

内存存储

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

例如,要存储博客文章。

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

  1. type Post struct {
  2. Id int
  3. Content string
  4. Author string
  5. }

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

  1. var PostById map[int]*Post

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

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

  1. var PostByAuthor map[string][]*Post

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

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

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

  1. func store(post *Post) {
  2. PostById[post.Id] = post
  3. PostByAuthor[post.Author] = append(PostByAutor[post.Autor], post)
  4. }

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

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

例如:

  1. // 按文章Id检索文章并输出文章的Content
  2. fmt.Println(PostById[1])
  3. fmt.Println(PostById[2])
  4. // 按作者检索文章并输出文章的Content
  5. for _, post := range PostByAuthor["userA"]{
  6. fmt.Println(post)
  7. }

下面是完整的代码:

  1. package main
  2. import (
  3. "fmt"
  4. )
  5. type Post struct {
  6. Id int
  7. Content string
  8. Author string
  9. }
  10. // 用于存储的两个内存容器
  11. var PostById map[int]*Post
  12. var PostsByAuthor map[string][]*Post
  13. // 存储数据
  14. func store(post *Post) {
  15. PostById[post.Id] = post
  16. PostsByAuthor[post.Author] = append(PostsByAuthor[post.Author], post)
  17. }
  18. func main() {
  19. PostById = make(map[int]*Post)
  20. PostsByAuthor = make(map[string][]*Post)
  21. post1 := &Post{Id: 1, Content: "Hello 1", Author: "userA"}
  22. post2 := &Post{Id: 2, Content: "Hello 2", Author: "userB"}
  23. post3 := &Post{Id: 3, Content: "Hello 3", Author: "userC"}
  24. post4 := &Post{Id: 4, Content: "Hello 4", Author: "userA"}
  25. store(post1)
  26. store(post2)
  27. store(post3)
  28. store(post4)
  29. fmt.Println(PostById[1])
  30. fmt.Println(PostById[2])
  31. for _, post := range PostsByAuthor["userA"] {
  32. fmt.Println(post)
  33. }
  34. for _, post := range PostsByAuthor["userC"] {
  35. fmt.Println(post)
  36. }
  37. }
 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号