douyan2002 2017-04-11 02:56
浏览 34
已采纳

具有许多参数的构造函数

What's the most idiomatic way of initializing a Go type with many required parameters?

For example:

type Appointment struct {
  Title string
  Details string
  Dresscode string

  StartingTime int64
  EndingTime int64
  RSVPdate int64


  Place *Place
  Guests []*Guest
}

type Place struct {
  Name string
  Address string
}

type Guest struct {
  Name string
  Status string
}

I want the Appointment type to be always valid; that is, I don't want to initialize it with a struct literal and then have to validate it.

Don't want:

a := &Appointment{
  Title: "foo",
  Details: "bar",
  StartingTime: 12451412,
  ...
}

err := a.Validate()

whats the best way to initialize this type of object (with lots of fields) without having to supply all the arguments in the constructor arguments?

  • 写回答

4条回答 默认 最新

  • dporu02280 2017-04-11 09:14
    关注

    One way you could avoid having to pass 10+ arguments to your constructors is to have an XxxParams type for each of your Xxx types and have your NewXxx take that params type as its argument. Then the NewXxx constructor would construct an Xxx value from those params, validate it, and return it, or an error, depending on the result of the validation.

    This might feel redundant if you're constructing the XxxParams values manually as opposed to unmarshaling them from json, xml, etc.; but still, this way you are enforcing, however loosely, only valid Xxx's to be constructed, keeping the possibly invalid state in the input (XxxParams).

    Here's an example from Stripe's repo: Account, AccountParams, and constructor

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错