go函数的可变长参数_如何在Go中使用可变参数函数

go函数的可变长参数

介绍 (Introduction)

A variadic function is a function that accepts zero, one, or more values as a single argument. While variadic functions are not the common case, they can be used to make your code cleaner and more readable.

可变参数函数是接受零,一个或多个值作为单个参数的函数。 尽管可变参数函数不是常见的情况,但是可以使用可变参数函数使您的代码更整洁,更具可读性。

Variadic functions are more common than they seem. The most common one is the Println function from the fmt package.

可变参数功能比看起来更普遍。 最常见的一种是fmt软件包中的Println函数。

func Println(a ...interface{}) (n int, err error)

A function with a parameter that is preceded with a set of ellipses (...) is considered a variadic function. The ellipsis means that the parameter provided can be zero, one, or more values. For the fmt.Println package, it is stating that the parameter a is variadic.

甲功能与前面带有一组椭圆的参数( ... )被认为是一个可变参数函数。 省略号表示提供的参数可以是零,一个或多个值。 对于fmt.Println包,它说明参数a是可变参数。

Let’s create a program that uses the fmt.Println function and pass in zero, one, or more values:

让我们创建一个使用fmt.Println函数并传递零,一个或多个值的程序:

print.go
print.go
package main

import "fmt"

func main() {
    fmt.Println()
    fmt.Println("one")
    fmt.Println("one", "two")
    fmt.Println("one", "two", "three")
}

The first time we call fmt.Println, we don’t pass any arguments. The second time we call fmt.Println we pass in only a single argument, with the value of one. Then we pass one and two, and finally one, two, and three.

第一次调用fmt.Println ,我们不传递任何参数。 第二次调用fmt.Println我们仅传递一个参数,值为one 。 然后我们通过onetwo ,最后是onetwothree

Let’s run the program with the following command:

让我们使用以下命令运行该程序:

  • go run print.go

    去运行print.go

We’ll see the following output:

我们将看到以下输出:


   
   
   
     
     
     
     
Output
one one two one two three

The first line of the output is blank. This is because we didn’t pass any arguments the first time fmt.Println was called. The second time the value of one was printed. Then one and two, and finally one, two, and three.

输出的第一行为空白。 这是因为第一次fmt.Println时没有传递任何参数。 第二次打印one值。 然后是onetwo ,最后是onetwothree

Now that we have seen how to call a variadic function, let’s look at how we can define our own variadic function.

现在,我们已经了解了如何调用可变参数函数,让我们看一下如何定义自己的可变参数函数。

定义可变函数 (Defining a Variadic Function)

We can define a variadic function

你可能感兴趣的:(字符串,python,java,编程语言,go)