5

go存储之内存_zzxiaoma的技术博客_51CTO博客

 1 year ago
source link: https://blog.51cto.com/u_3764469/5576343
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

go存储之内存

原创

zzxiaoma 2022-08-15 08:25:45 博主文章分类:go ©著作权

文章标签 赋值 初始化 数据库 文章分类 Go语言 编程语言 yyds干货盘点 阅读数195

在web应用中需要存储用户录入的信息,一般是使用数据库来存储,这里使用内存的形式来存储数据,主要用于演示数据存储到go类型map中。

package main

import (
"fmt"
)

type Person struct {
Id int
Name string
}

var PersonById map[int]*Person
var PersonByName map[string][]*Person

func store(person Person) {
PersonById[person.Id] = &person
PersonByName[person.Name] = append(PersonByName[person.Name], &person)
}

func main() {
PersonById = make(map[int]*Person)
PersonByName = make(map[string][]*Person)

person1 := Person{Id: 1, Name: "刘备"}
person2 := Person{Id: 2, Name: "关羽"}
person3 := Person{Id: 3, Name: "张飞"}
person4 := Person{Id: 4, Name: "刘备"}

store(person1)
store(person2)
store(person3)
store(person4)

fmt.Println(PersonById[1])
fmt.Println(PersonById[2])
for _, person := range PersonByName["刘备"] {
fmt.Println(person)
}

}

先定义一个结构体Person,定义2个map类型,1个是用户id为key,1个是用户名称为key。store是存储函数,往2个map中添加数据。

PersonById是直接根据id进行赋值,PersonByName中的value是一个切片,所以使用append进行添加。在main方法中先初始化4个Persion,然后把这4个Persion存入到map中,最后进行打印输出。这样就可以在其他地方对PersonById和PersonByName进行使用。

  • 收藏
  • 评论
  • 分享
  • 举报

上一篇:go基础之json


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK