• 函数的不定参数你会用吗?


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

    案例

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

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

    以上。

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

    作者:新亮笔记(关注公众号,可申请添加微信好友)
    出处:https://www.cnblogs.com/xinliangcoder
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

  • 相关阅读:
    怎么产生一个随机数
    C# 算速表达式
    Wpf OpenFileDialog
    完美世界自动更新程序
    只容许程序运行1个实例
    WPF 同一个程序 只允许 同时运行一个
    13 引用WINAPI
    winform窗体跟随窗体
    C#如何检测一个字符串是不是合法的URL
    WPF 下载网络文件 带进度条
  • 原文地址:https://www.cnblogs.com/xinliangcoder/p/14966165.html
Copyright © 2020-2023  润新知