将map键值对转换为golang中结构体中的两个字段
我正在尝试将映射的键值对转换为我拥有的结构的两个字段,但在执行此操作时遇到一些问题。
type A struct{
Name string
Value float64
}
type B struct {
ListOfMetrics []*A
}
func (n *A) UnmarshalYAML(unmarshal func(interface{}) error) error {
type origA struct {
Metrics map[string]float64 `protobuf:"bytes,2,opt,name=metric" json:"metrics"`
ListOfMetrics []*A
}
var oN origA
err := unmarshal(&oN)
if err != nil {
return err
}
var Dp []*A
for metric, value := range oN.Metrics {
fmt.Println(metric, value)
n := A{}
n.Metric = metric
n.Value = value
Dp = append(Dp, &n)
}
oN.ListOfMetrics = Dp
var m *B
m.ListOfMetrics = oN.ListOfMetrics
return nil
基本上,我试图将 map[string]float64
的 Metrics 字段转换为 Metric name string
和 Metric value float64
的结构,这需要将存储为指标名称和值的列表。有人可以帮忙吗?
I am trying to convert a map's key value pair into a struct's two fields that I have, but facing some issue while doing it.
type A struct{
Name string
Value float64
}
type B struct {
ListOfMetrics []*A
}
func (n *A) UnmarshalYAML(unmarshal func(interface{}) error) error {
type origA struct {
Metrics map[string]float64 `protobuf:"bytes,2,opt,name=metric" json:"metrics"`
ListOfMetrics []*A
}
var oN origA
err := unmarshal(&oN)
if err != nil {
return err
}
var Dp []*A
for metric, value := range oN.Metrics {
fmt.Println(metric, value)
n := A{}
n.Metric = metric
n.Value = value
Dp = append(Dp, &n)
}
oN.ListOfMetrics = Dp
var m *B
m.ListOfMetrics = oN.ListOfMetrics
return nil
Basically I am trying to get the Metrics field of map[string]float64
into a struct of Metric name string
and Metric value float64
, which needs to be stored as a list of metric name and values. Can anyone please help?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的方法 UnmarshalYAML 是为 A 定义的,但 A 只是一对。
对我来说..把它放在 B 中是有道理的
而且你的逻辑看起来很复杂。您使用内容创建一个局部变量,并且无法从外部恢复它(无需额外的努力)
我使用 json 作为基础编写了一个小示例,可以作为起点
https://go.dev/play/p/13lDeu3BkwQ
Your method UnmarshalYAML is defined for A, but A is just a pair.
For me.. make sense put it in B
Also your logic seems complex. You create a local variable with your content and there is no way to recover it from outside (without an extra effort)
I wrote a small example using json as base, can be a starting point
https://go.dev/play/p/13lDeu3BkwQ