duanjuan3931
2014-05-05 21:37
浏览 507
已采纳

Golang:映射到struct

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?

图片转代码服务由CSDN问答提供 功能建议

由于某种原因(解析定长数据文件),我有一张地图,我想要

让我们说:

  type Point struct {X,Y int} 
point:= make  (map [string] int)
 
point [“ X”] = 15 
point [“ Y”] = 13 
 
p:= Point {point} //无效
  <  / pre> 
 
 

我该怎么做? 还是我走错了路?

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dongpa2000 2014-05-05 21:47
    已采纳

    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"]}
    
    已采纳该答案
    打赏 评论
  • douyi02577 2017-03-31 11:02

    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.

    打赏 评论

相关推荐 更多相似问题