Golang:将map转换为struct

huangapple go评论86阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2014年5月6日 05:37:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/23482345.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定