If multiple parameters need to be passed in a method and some parameters are not mandatory, what should be done?
Case study
// NewFriend 寻找志同道合朋友
func NewFriend(sex int, age int, hobby string) (string, error) {
// 逻辑处理 ...
return "", nil
}
NewFriend()
, the parameters sex
and age
method are optional parameters, how to write the method at this time?
Use indefinite parameters to pass parameters!
Think about how to achieve it?
Can I write it like this?
// 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
}
Is there a better solution?
Transfer structure... Well, this is also a way.
Let’s take a look at how other people’s open source code is written. What I learned is the grpc.Dial(target string, opts …DialOption)
method, which is WithXX
method, for example:
conn, err := grpc.Dial("127.0.0.1:8000",
grpc.WithChainStreamInterceptor(),
grpc.WithInsecure(),
grpc.WithBlock(),
grpc.WithDisableRetry(),
)
Compared with the gourd painting, what I achieved is like this, you can take a look:
// 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
}
}
When used, call it like this:
friends, err := friend.NewFriend(
"看书",
friend.WithAge(30),
friend.WithSex(1),
)
if err != nil {
fmt.Println(friends)
}
If you write in this way, if you add other parameters, will it be easy to configure?
the above.
If you have any questions about the above, come and communicate with my planet~ https://t.zsxq.com/iIUVVnA
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。