英文:
Convert list of struct to a list of another struct when second struct uses a subset of fields
问题
我有两个结构体,Foo
和Bar
。Bar
使用了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 Foo
s to Bar
s. 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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论