Convert list of struct to a list of another struct when second struct uses a subset of fields

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

Convert list of struct to a list of another struct when second struct uses a subset of fields

问题

我有两个结构体,FooBarBar使用了Foo字段的一个子集:

type Foo struct {
	Id    string
	Name  string
	Extra string
}

type Bar struct {
	Id   string
	Name string
}

我想将Foo转换为Bar。我目前是这样做的:

bars := []Bar

for _, foo = range foos {
    bars = append(
        bars,
        Bar{Id: foo.Id, Name: foo.name}
    )
}

在Go语言中有更好的方法吗?

英文:

I have two structs, Foo and Bar. Bar uses a subset of of Foo fields:

type Foo struct {
	Id    string
	Name  string
	Extra string
}

type Bar struct {
	Id   string
	Name string
}

I want to convert Foos to Bars. I'm currently doing it like this:

bars := []Bar

for _, foo = range foos {
    bars = append(
        bars,
        Bar{Id: foo.Id, Name: foo.name}
    )
}

Is there a better way to do this in Go?

答案1

得分: 1

你可以将 Bar 嵌入到 Foo 中。

type Foo struct {
    Bar
    Extra string
}

type Bar struct {
    Id   string
    Name string
}
var bars []Bar

for _, foo = range foos {
    bars = append(bars, foo.Bar)
}
英文:

You can embed Bar into Foo.

type Foo struct {
    Bar
    Extra string
}

type Bar struct {
    Id   string
    Name string
}
var bars []Bar

for _, foo = range foos {
    bars = append(bars, foo.Bar)
}

答案2

得分: 1

在你的问题中,你说Bar包含一部分字段,但是你不能让Foo包含一个Bar。这告诉我它们实际上不是一个子集,而是无关的结构体。

为了在代码中更清晰地表达你的意图,你可以在Foo上执行ToBar,像这样:

type Foo struct {
    Id    string
    Name  string
    Extra string
}

func (foo *Foo) ToBar() Bar {
    return Bar{Id: foo.Id, Name: foo.Name}
}

type Bar struct {
    Id   string
    Name string
}
英文:

In your question you state that Bar contains a subset of fields but you cannot have Foo contain a Bar. This tells me that they are in-fact not a subset and are unrelated structs.

As a possible way to keep your intentions clearer in your code, you could do ToBar on the Foo something like this:

type Foo struct {
	Id    string
	Name  string
	Extra string
}

func (foo *Foo) ToBar() Bar {
	return Bar{Id: foo.Id, Name: foo.Name}
}

type Bar struct {
	Id   string
	Name string
}

huangapple
  • 本文由 发表于 2021年7月19日 17:44:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/68438374.html
匿名

发表评论

匿名网友

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

确定