go基础之不定参函数

go语言同其他编程一样也提供了对变参函数的支持。本文简单讲解一下go中变参函数的使用方法。

指定类型参数

不定参数是指函数传入参数的个数为不确定数量,个数需要在调用的时候才能得到确定。go语言中接受不定参数的函数的原型如下所示:

func myfunc(args ...type)

func myfunc(arg1 int, args ...type)

这段代码的意思是,函数func()接受不定数量的参数,这些参数的类型全部是type。形如…type格式的类型只能作为函数的参数类型存在,并且必须是最后一个参数。它是一个语法糖( syntactic sugar),即这种语法对语言的功能并没有影响,但是更方便程序员使用。通常来说,使用语法糖能够增加程序的可读性,从而减少程序出错的机会。
从内部实现机理上来说,类型…type本质上是一个数组切片,也就是[]type。

func myfunc(args ...int) {
    for _, arg := range args {
        fmt.Println(arg)
    }
}

参数args可以用for循环来获得每个传入的参数。假如没有…type这样的语法糖,开发者将不得不这么写:

func myfunc2(args []int) {
    for _, arg := range args {
        fmt.Println(arg)
    }
}

myfunc和myfunc2从函数的实现角度来看并没有太大的区别。从调用的角度来看,myfunc2则比较简洁,不用显示加上[]int{}来构造一个数组切片实例。

myfunc2([]int{1, 3, 7, 13})

虽然我们定义了…type,但是可以不传入参数。看下面的示例:

package main

import (  
    "fmt"
)

func find(num int, nums ...int) {  
    fmt.Printf("type of nums is %T\n", nums)
    found := false
    for i, v := range nums {
        if v == num {
            fmt.Println(num, "found at index", i, "in", nums)
            found = true
        }
    }
    if !found {
        fmt.Println(num, "not found in ", nums)
    }
    fmt.Printf("\n")
}
func main() {  
    find(1, 2, 1, 4)
    find(5)
}
type of nums is []int  
1 found at index 1 in [2 1 4]

type of nums is []int  
5 not found in  []  

find(5)这个调用中只有传入了一个参数。没有传递任何参数给 nums …int。这是合法的,如果没有给可变参数传递任何值,则可变参数为 nil 切片,在这里 nums 是一个 nil 切片,长度和容量都是0

任意类型参数的变参

上面的例子将不定参数类型约束为type,固定为type类型,如果你希望传任意类型并且任意个参数,可以指定类型为
interface{}。原型如下:

func myfunc3(args ...interface{}) {
// ...
}
func myfunc3(arg1 string, args ...interface{}) {
// ...
}

用interface{}传递任意类型数据是Go语言的惯例用法。使用interface{}仍然是类型安全的,

package main
import "fmt"
func MyPrintf(args ...interface{}) {
    for _, arg := range args {
        switch arg.(type) {
            case int:
                fmt.Println(arg, "is an int value.")
            case string:
                fmt.Println(arg, "is a string value.")
            case int64:
                fmt.Println(arg, "is an int64 value.")
            default:
                fmt.Println(arg, "is an unknown type.")
        }
    }
}
func main() {
    var v1 int = 1
    var v2 int64 = 1111
    var v3 string = "hello world!"
    var v4 float32 = 1.1111
    MyPrintf(v1, v2, v3, v4)
}

//输出为:

1 is an int value.
1111 is an int64 value.
hello world is a string value.
1.1111 is an unknown type.

猜你喜欢

转载自blog.csdn.net/hjxzb/article/details/80932370
今日推荐