Spread operator analogue

狂风中的少年 提交于 2021-01-29 12:49:36

问题


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"
}

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"
  }
}

回答1:


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
}

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)

Output (try it on the Go Playground):

[{AK93-KADJ9-92J76 Other value MSLA-923-OKSW}
    {AK93-KADJ9-92J76 Yet another value MSLA-923-OKSW}]

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.

For example:

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
}

And then using it:

var slc = []Obj{
    ValidObject.withCode("code2").withSsid("ssid2"),
    ValidObject.withMit("mit2").withSsid("ssid3"),
}
fmt.Println(slc)

Output (try it on the Go Playground):

[{ssid2 code2 MSLA-923-OKSW} {ssid3 SKO-120O mit2}]



回答2:


Create a slice of struct var objCollector = []obj{} globally and read data into the defined struct and append the object into slice of struct that we created.

type Obj struct {
    ssid string
    code string
    mit  string
}

var objCollector = []obj{}

func main() {
    var ValidObject = Obj{
        ssid: "AK93-KADJ9-92J76",
        code: "SKO-120O",
        mit:  "MSLA-923-OKSW",
    }
    append(objectCollector, ValidObject)
}


来源:https://stackoverflow.com/questions/52440765/spread-operator-analogue

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!