如果一个方法中需要传递多个参数且某些参数又是非必传,应该如何处理?
// NewFriend 寻找志同道合朋友
func NewFriend(sex int, age int, hobby string) (string, error) {
// 逻辑处理 ...
return "", nil
}
NewFriend()
,方法中参数 sex
和 age
为非必传参数,这时方法如何怎么写?
传参使用不定参数!
想一想怎么去实现它?
看一下这样写可以吗?
// 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)
}
这样写如果新增其他参数,是不是也很好配置呀。
以上。
对以上有疑问,快来我的星球交流吧 ~ https://t.zsxq.com/iIUVVnA
背景 在公司参与一个原生APP和h5混合开发的项目,本人在项目中负责h5部分,现将...
简介: 6月4日,以“开启分布式云新时代”为主题2021云边协同大会在北京举行,本...
1、纯工具操作步骤,懂代码更容易 划线就是不符合国人的审美观念,看着就别扭,...
折叠式卡片布局在PC版网站中可能不常见,但是在手机版,小屏幕的网页浏览会大发...
1.先瞧瞧效果: 2.代码是这样的: img src=images/circle.png alt= id=circle/@m...
本文没有咬文嚼字的地方,只是一个配色技巧的分享,十分简单,简单到流泪,但或...
前言 Canvas绘制多变形非常简单,只要懂得Canvas路径 + 简单的初中数学知识即可...
在默认情况之下,如果在Canvas之中将某个物体(源)绘制在另一个物体(目标)之...
作者:Joe Seifi 译者:前端小智 移动: https://mp.weixin.qq.com/s/p5... 有梦...
一、虽然有的属性是boolean类型,但仍旧建议按照XHTML书写(属性名=属性值)格式...