英文:
Golang: map to struct
问题
由于某种原因(固定长度的数据文件解析),我有一个映射(map),我想将映射的元素保存在一个结构体中。
假设:
type Point struct {X, Y int}
point := make(map[string]int)
point["X"] = 15
point["Y"] = 13
p := Point{point} // 这样不起作用
我该如何做?或者我走错了方向吗?
英文:
For some reason (fixed-length data file parsing), I've got a map and I want the elements of the map being saved in a struct.
Let's say:
type Point struct {X, Y int}
point := make(map[string]int)
point["X"] = 15
point["Y"] = 13
p := Point{point} // doesn't work
How do I do that? Or have I taken the wrong path?
答案1
得分: 2
据我所知,除非你使用encoding
包,否则无法像这样进行自动映射。但你可以使用以下方式:
p := Point{X: point["X"], Y: point["Y"]}
英文:
As far as I know you cant have automatic mapping like this unless you're using the encoding
package, but you can use the following way:
p := Point{X: point["X"], Y: point["Y"]}
答案2
得分: 0
如果效率不是很重要,你可以将地图转换为JSON字节并将其解析回结构体。
import "encoding/json"
type Point struct {X, Y int}
point := make(map[string]int)
point["X"] = 15
point["Y"] = 13
bytes, err := json.Marshal(point)
var p Point
err = json.Unmarshal(bytes, &p)
这样做可以使代码在结构体包含大量字段时更容易修改。
英文:
If the efficiency is not so important, you can marshal the map into JSON bytes and unmarshal it back to a struct.
import "encoding/json"
type Point struct {X, Y int}
point := make(map[string]int)
point["X"] = 15
point["Y"] = 13
bytes, err := json.Marshal(point)
var p Point
err = json.Unmarshal(bytes, &p)
This maks the code easier to be modified when the struct contains a lot of fields.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论