英文:
How to fill a Struct type map from Mysql
问题
我是你的中文翻译助手,以下是你提供的代码的翻译:
我是Golang的新手。
这是我想要加载的结构,问题是有一个名为Channels
的map[string]ChannelST
,我不知道如何从Mysql中填充它。
type StreamST struct {
Name string
Channels map[string]ChannelST
}
type ChannelST struct {
Name string
URL string
OnDemand bool
Debug bool
Status int
runLock bool
codecs []av.CodecData
sdp []byte
signals chan int
hlsSegmentBuffer map[int]SegmentOld
hlsSegmentNumber int
clients map[string]ClientST
ack time.Time
}
希望能对你有所帮助!
英文:
Im new in Golang.
This is the structure that I want to load and the problem is that there is the map [string] ChannelST which I don't know how to fill from Mysql
type StreamST struct {
Name string
Channels map[string]ChannelST
}
type ChannelST struct {
Name string
URL string
OnDemand bool
Debug bool
Status int
runLock bool
codecs []av.CodecData
sdp []byte
signals chan int
hlsSegmentBuffer map[int]SegmentOld
hlsSegmentNumber int
clients map[string]ClientST
ack time.Time
答案1
得分: 0
确切的答案很大程度上取决于你的数据库模式。我将尝试给出一个通用的答案。你可以有两种方式(据我所知):
- 使用一些库来帮助你完成这方面的工作,比如sqlx或gorm。这些库会查看你的结构体中的导出字段和标签,并自动填充它们。
- 使用标准的sql库,自己完成所有的操作。在这种情况下,你需要使用
Rows.Scan
函数来手动填充结构体。
无论哪种方式,你的StreamST
结构体包含一个map,它是一个集合,所以我假设你正在连接两个表。在GORM中,你可以指定关系,库会考虑这一点。不过我不确定这是否只适用于切片,还是对于map也有效,因为GORM不知道要使用结构体的哪个字段作为map的索引。
当使用标准库时,返回的行与SQL查询结果完全相同,所以左表的字段会重复,因此你需要编写自己的逻辑将这些字段列表转换为正确的结构。
最后,你有一些自定义类型,比如av.CodecData
。如果这些类型对应于自定义格式的单个字段,你可以让这些结构体实现sql.Scanner和driver.Valuer接口来实现自定义的编码/解码。
英文:
The exact answer depends a lot on your database schema. I will attempt to give a generic answer. You could go 2 ways(as far as I know):
- Use a library which does a lot of you in this regard like sqlx or gorm. These libraries will look at the exported fields in your struct and tags to automatically fill them.
- Use the standard sql library and do everything yourself. In this case you will need to use the
Rows.Scan
function to fill structs yourself.
In any case, your StreamST
struct contains a map, which is a collection, so I assume you are joining two tables. In GORM you can specify relations and the library will take this into account. Though I am not sure if this only works for slices or maps as well, since GORM doesn't know which field of struct to use as index for the map.
When using the standard library, the rows returned are exactly the same as the result from the SQL query, so fields of your left table will be repeated and thus you need to write your own logic to turn this list of fields into the proper structure.
Lastly, you have a number of custom types like av.CodecData
. If these correspond to single fields but in a custom format, you can implement custom encoding/decoding by letting these structs implement sql.Scanner and driver.Valuer interfaces.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论