如果一个方法中需要传递多个参数且某些参数又是非必传,应该如何处理?

案例

  1. // NewFriend 寻找志同道合朋友
  2. func NewFriend(sex int, age int, hobby string) (string, error) {
  3. // 逻辑处理 ...
  4. return "", nil
  5. }

NewFriend(),方法中参数 sexage 为非必传参数,这时方法如何怎么写?

传参使用不定参数!

想一想怎么去实现它?

看一下这样写可以吗?

  1. // Sex 性别
  2. type Sex int
  3. // Age 年龄
  4. type Age int
  5. // NewFriend 寻找志同道合的朋友
  6. func NewFriend(hobby string, args ...interface{}) (string, error) {
  7. for _, arg := range args {
  8. switch arg.(type) {
  9. case Sex:
  10. fmt.Println(arg, "is sex")
  11. case Age:
  12. fmt.Println(arg, "is age")
  13. default:
  14. fmt.Println("未知的类型")
  15. }
  16. }
  17. return "", nil
  18. }

有没有更好的方案呢?

传递结构体… 恩,这也是一个办法。

咱们看看别人的开源代码怎么写的呢,我学习的是 grpc.Dial(target string, opts …DialOption) 方法,它都是通过 WithXX 方法进行传递的参数,例如:

  1. conn, err := grpc.Dial("127.0.0.1:8000",
  2. grpc.WithChainStreamInterceptor(),
  3. grpc.WithInsecure(),
  4. grpc.WithBlock(),
  5. grpc.WithDisableRetry(),
  6. )

比着葫芦画瓢,我实现的是这样的,大家可以看看:

  1. // Option custom setup config
  2. type Option func(*option)
  3. // option 参数配置项
  4. type option struct {
  5. sex int
  6. age int
  7. }
  8. // NewFriend 寻找志同道合的朋友
  9. func NewFriend(hobby string, opts ...Option) (string, error) {
  10. opt := new(option)
  11. for _, f := range opts {
  12. f(opt)
  13. }
  14. fmt.Println(opt.sex, "is sex")
  15. fmt.Println(opt.age, "is age")
  16. return "", nil
  17. }
  18. // WithSex sex 1=female 2=male
  19. func WithSex(sex int) Option {
  20. return func(opt *option) {
  21. opt.sex = sex
  22. }
  23. }
  24. // WithAge age
  25. func WithAge(age int) Option {
  26. return func(opt *option) {
  27. opt.age = age
  28. }
  29. }

使用的时候这样调用:

  1. friends, err := friend.NewFriend(
  2. "看书",
  3. friend.WithAge(30),
  4. friend.WithSex(1),
  5. )
  6. if err != nil {
  7. fmt.Println(friends)
  8. }

这样写如果新增其他参数,是不是也很好配置呀。

以上。

对以上有疑问,快来我的星球交流吧 ~ https://t.zsxq.com/iIUVVnA