问题描述
我有一个结构和该结构的实例:
I have a struct and the instance of that struct:
type Obj struct {
ssid string
code string
mit string
// and other props (23)
}
var ValidObject = Obj {
ssid: "AK93-KADJ9-92J76",
code: "SKO-120O"
mit: "MSLA-923-OKSW"
}
我想创建一个切片结构( Obj
),该切片将包含 ValidObject
且仅更改了某些字段.我认为最好的解释方法是使用伪代码,所以这里是(使用JS的散布运算符)):
I want to create a slice of structs (Obj
) which will contain ValidObject
with only some fields changed. I think the best way to explain that would be using pseudo code, so here it is (using spread operator from JS :) ):
var slc = []Obj{
{
...ValidObject,
code: "Other value",
},
{
...ValidObject,
mit: "Other value"
}
}
推荐答案
创建一个辅助函数,该函数需要一个 Object
,更改其 code
并返回新的对象
:
Create a helper function that takes an Object
, changes its code
and returns the new Object
:
func withCode(obj Obj, code string) Obj {
obj.code = code
return obj
}
请注意, withCode
采用非指针值,因此您传递的 Object
不会被修改,只会修改本地副本.
Note that withCode
takes a non-pointer value, so the Object
you pass will not be modified, only the local copy.
使用此功能,您的任务是:
And using this your task is:
var slc = []Obj{
withCode(ValidObject, "Other value"),
withCode(ValidObject, "Yet another value"),
}
fmt.Println(slc)
输出(在游乐场上尝试):
[{AK93-KADJ9-92J76 Other value MSLA-923-OKSW}
{AK93-KADJ9-92J76 Yet another value MSLA-923-OKSW}]
该帮助程序 withCode
甚至可以是方法(不是函数).
This helper withCode
could even be a method (not a function).
请注意,如果您需要多个字段的变体,最好将它们添加为方法,以便可以链接调用.
Note that if you need to have variations of many fields, it would probably be better to add these as methods, so you can chain the calls.
例如:
func (o Obj) withCode(code string) Obj {
o.code = code
return o
}
func (o Obj) withSsid(ssid string) Obj {
o.ssid = ssid
return o
}
func (o Obj) withMit(mit string) Obj {
o.mit = mit
return o
}
然后使用它:
var slc = []Obj{
ValidObject.withCode("code2").withSsid("ssid2"),
ValidObject.withMit("mit2").withSsid("ssid3"),
}
fmt.Println(slc)
输出(在游乐场上尝试):
[{ssid2 code2 MSLA-923-OKSW} {ssid3 SKO-120O mit2}]
这篇关于传播操作员模拟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!