创建一个辅助函数,它需要Object
,改变其code
并返回新的Object
:
func withCode(obj Obj, code string) Obj {
obj.code = code
return obj
}
注意withCode
采用非指针值,因此Object
你的pass不会被修改,只是本地副本。
使用它你的任务是:
var slc = []Obj{
withCode(ValidObject, "Other value"),
withCode(ValidObject, "Yet another value"),
}
fmt.Println(slc)
输出(尝试一下去游乐场 https://play.golang.org/p/s2hq0qPBFxO):
[{AK93-KADJ9-92J76 Other value MSLA-923-OKSW}
{AK93-KADJ9-92J76 Yet another value MSLA-923-OKSW}]
这个帮手withCode
甚至可以是一种方法(而不是函数)。
请注意,如果您需要多个字段的变体,最好将它们添加为方法,以便您可以链接调用。
例如:
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)
输出(尝试一下去游乐场 https://play.golang.org/p/SL-VXhnHXyp):
[{ssid2 code2 MSLA-923-OKSW} {ssid3 SKO-120O mit2}]