比如

// NewFriend 寻找志同道合朋友
func NewFriend(sex int, age int, hobby string) (string, error) {
 
 // 逻辑处理 ...

 return "", nil
}

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

一:

// Sex 性别
type Sex int

// Age 年龄
type Age int

// NewFriend 寻找志同道合的朋友
func NewFriend(hobby string, args ...interface{}) (string, error) {
 for _, arg := range args {
  switch arg.(type) {
  case Sex:
   fmt.Println(arg, "is sex")
  case Age:
   fmt.Println(arg, "is age")
  default:
   fmt.Println("未知的类型")
  }
 }
 return "", nil
}

有没有更好的方案呢?传递结构体也是个不错的方法!

// Option custom setup config
type Option func(*option)

// option 参数配置项
type option struct {
 sex int
 age int
}

// NewFriend 寻找志同道合的朋友
func NewFriend(hobby string, opts ...Option) (string, error) {
 opt := new(option)
 for _, f := range opts {
  f(opt)
 }

 fmt.Println(opt.sex, "is sex")
 fmt.Println(opt.age, "is age")

 return "", nil
}

// WithSex sex 1=female 2=male
func WithSex(sex int) Option {
 return func(opt *option) {
  opt.sex = sex
 }
}

// WithAge age
func WithAge(age int) Option {
 return func(opt *option) {
  opt.age = age
 }
}

使用的时候这样调用:

friends, err := friend.NewFriend(
 "看书",
 friend.WithAge(30),
 friend.WithSex(1),
)

if err != nil {
 fmt.Println(friends)
}