前言
在许多语言中都有变参函数的语法糖,那么golang也不例外,这次我们就来试试golang中的变参函数如何使用吧~
定义
众多语言中,例如Java的变参方法长这样:
public class JueJinApplication implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(JueJinApplication.class, args);
}
@Override
public void run(String... strings) throws Exception{
System.out.println(Arrays.toString(strings)); //打印可变参数
}
}
Go的写法和Java也有点相似之处,都是使用...在形参前后进行定义:
func Println(args ...interface{}) {
fmt.Println(args...)
}
func main() {
Println("a", 1, 2, 3.5, errors.New("error"))
}
场景
在Golang的内置库中,大量使用了变参函数,比如我们常用的fmt.Println,它的定义是这样的:
// Println formats using the default formats for its operands and writes to standard output.
// Spaces are always added between operands and a newline is appended.
// It returns the number of bytes written and any write error encountered.
func Println(a ...interface{}) (n int, err error) {
return Fprintln(os.Stdout, a...)
}
接下来我们就来实验写两个小方法,一个是获取一组数值中最小数值,另外一个是计算一组数值的平均值,将变参函数用起来。
获取一组数值中最小数值
func GetMinNumber(args ...int) (res int) {
for i, arg := range args {
if i == 0{
res = arg
continue
}
if arg < res{
res = arg
}
}
return
}
func main() {
fmt.Printf("最小数值为:%d\n", GetMinNumber(63, 75, 2, 65, 1, 55))
}
打印结果:
最小数值为:1
计算一组数值的平均值
func GetAverage(args ...float32) (res float32) {
var sum float32
for _, arg := range args {
sum += arg
}
return sum / float32(len(args))
}
func main() {
fmt.Printf("平均数值为:%f\n", GetAverage(3.66, 2.55, 10, 150, 65))
}
打印结果为:
平均数值为:46.241997
后记
在实际开发中,有许多地方都会用到变参函数,比如日志打印,配置参数等等,至于具体什么时候使用变参函数,应该大部分情况都是在不确定参数的个数的情况下使用。
最后,感谢您的阅读,谢谢!