登录
首页 >  Golang >  Go问答

处理 `New(...` 函数中冗长参数列表的方法

来源:stackoverflow

时间:2024-02-29 23:00:25 174浏览 收藏

大家好,我们又见面了啊~本文《处理 `New(...` 函数中冗长参数列表的方法》的内容中将会涉及到等等。如果你正在学习Golang相关知识,欢迎关注我,以后会给大家带来更多Golang相关文章,希望我们能一起进步!下面就开始本文的正式内容~

问题内容

假设我有一个名为 mystruct 的本地化结构,其主体如下:

struct mystruct {
  myfield1 string
  myfield2 string
  myfield3 string
  ...
  myfieldn string
}

还有一个为外部调用者实例化新 mystructs 的函数:

func newmystruct(myfield1, myfield2, myfield3, ..., myfieldn string) mystruct {
  return mystruct{
    myfield1: myfield1,
    myfield2: myfield2,
    myfield3: myfield3,
    ...
    myfieldn: myfieldn,
  }
}

问题:如何最好地处理结构中字段过多导致 newmystruct(... 函数参数过多的情况?方式 /strong> 有没有最佳实践来缓解这个问题?到目前为止,我的代码库中有几个这样的函数:

func NewSuperStruct(myField1, myField2, myField3, myField4, myField5, myField6, myField7, myField8, myField9, myField10, myField11, myField12, myField13, myField14, myField15, myField16, myField17, myField18, myField19, myField20, myField21, myField22) ...

但结构本身并不一定是无意义的,因为属性/字段不属于其中,在我的应用程序中它们确实有意义,结构太大了,仅此而已。


正确答案


我想说只是没有 new 函数:

struct mystruct {
  myfield1 string
  myfield2 string
  myfield3 string
}

val := mystruct{
    myfield1: "one",
    myfield2: "two",
    myfield3: "three",
}

如果需要从另一个包设置未导出的字段,请使用某种选项或配置:

type mystruct struct {
    exported   string
    unexported string
}

type mystructoptions struct {
    exported   string
    unexported string
}

func newmystruct(opts mystructoptions) *mystruct {
    return &mystruct{
        exported: opts.exported,
        unexported: opts.unexported,
    }
}

就我个人而言(显然取决于结构的目标),我非常喜欢功能选项:

type mystructopts func(*mystruct)

func withfield1(field1 string) mystructops {
  return func(m *mystruct) {
    m.myfield1 = field1
  }
}

func new(opts ...mystructopts) *mystruct {
  m := mystruct{
    myfield1: "somedefaultifneeded",
  }

  for _, opt := range opts {
    opt(&m)
  }

  return &m
}

可以按如下方式使用:

New(
  WithField1("someString"),
  ...
)

这有几个好处:

  • new 的调用者无需担心顺序
  • 通过字段名称明确传递值,这意味着您不会混淆 field1 和 field2
  • 您可以向 mystruct 传递不同的默认值,以防调用者不传递 withfield1
  • 添加更多字段不会导致必须更新 new 的所有调用者

理论要掌握,实操不能落!以上关于《处理 `New(...` 函数中冗长参数列表的方法》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>