函数的不定参数你是这样用吗?

简介: 函数的不定参数你是这样用吗?

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

案例

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

有没有更好的方案呢?

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

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

conn, err := grpc.Dial("127.0.0.1:8000",
 grpc.WithChainStreamInterceptor(),
 grpc.WithInsecure(),
 grpc.WithBlock(),
 grpc.WithDisableRetry(),
)

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

// 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)
}

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

目录
相关文章
|
10月前
在调用一个函数时传递了一个参数,但该函数定义中并未接受任何参数
在调用一个函数时传递了一个参数,但该函数定义中并未接受任何参数
101 2
|
11月前
|
Java
参数
在Java中,形式参数是函数或方法的参数。形式参数是在定义函数或方法时指定的变量,它们的作用是接收函数或方法调用时传递的实际参数的值。形式参数和实际参数是不同的,形式参数是在函数或方法内部使用的,而实际参数是在函数或方法调用时传递的值。
49 1
【学习笔记之我要C】函数的参数与调用
【学习笔记之我要C】函数的参数与调用
120 0
|
Java Scala 开发者
作为参数的函数 | 学习笔记
快速学习作为参数的函数
|
开发者 Python
函数的参数| 学习笔记
快速学习函数的参数
self.doubleSpinBox.setGeometry(QtCore.QRect(20, 25, 101, 22))参数讲解
self.doubleSpinBox.setGeometry(QtCore.QRect(20, 25, 101, 22))参数讲解
311 0
7.2 函数的参数
1、给 b 变量设定一个默认的值 如果实参传入的时候,指定了 b 的值,那 b 优先选择传入的实参,当 b 没有值时,才会用默认值 def funcA(a,b=0):     print(a)     print(b) funcA(1)        # b 变量选择默认实参...
609 0
|
C++
C++函数及参数
传值->传递的是数据副本(结构、普通数据类型数据) 传地址->传递的是数据变量的地址(数组等) 传值的缺点是需要复制数据副本,数据量大可能增加内存需求,降低系统运行速度; 传地址也有传地址的不好的地方,比如在不需要修改原数据的时候,一不小心把数据修改了,造成程序的违需求性;
945 0