Home >Backend Development >Golang >What are the syntax and type requirements for golang variable parameters?

What are the syntax and type requirements for golang variable parameters?

王林
王林Original
2024-04-30 08:12:02656browse

The variable parameter syntax in Go language is funcName(param1, param2, ..., paramN ...type), where param1 to paramN are fixed parameters and type is the type of variable parameters. Variadic parameters can only be slices, arrays, or variadic parameters themselves, such as ...string, ...[]int, ...func(string) int. The following example shows a function that accepts variable arguments and prints all arguments to the console: package mainimport "fmt"func printVarArgs(args ...string) { for _, arg := range args { fmt.Println(arg) }} func main() { printVarArgs("Hello", "World", "!", "This", "is", "an", "example") }, the output result is HelloWorld!Thisisanexample.

What are the syntax and type requirements for golang variable parameters?

Syntax and type requirements for variable parameters in Go language

Variable parameters are a method that allows a function to accept a variable number function of the parameters. In the Go language, variable parameters are represented by the ... operator.

Syntax

Variable parameters must be at the end of the parameter list. The syntax is as follows:

funcName(param1, param2, ..., paramN ...type)

Among them:

  • param1, param2, ..., paramN is Fixed parameters.
  • type is the type of variable parameter.

Type requirements

Variable parameters can only be slices, arrays, or variable parameters themselves (...type). For example:

  • funcName(param1, param2 ...string)
  • funcName(param1, param2 ...[]int)
  • funcName(param1, param2 ...func(string) int)

Practical case

The following example shows a function that accepts variadic arguments and prints all arguments to the console:

package main

import "fmt"

// printVarArgs 打印可变参数
func printVarArgs(args ...string) {
    for _, arg := range args {
        fmt.Println(arg)
    }
}

func main() {
    // 调用 printVarArgs 函数并传入可变参数
    printVarArgs("Hello", "World", "!", "This", "is", "an", "example")
}

Output:

Hello
World
!
This
is
an
example

The above is the detailed content of What are the syntax and type requirements for golang variable parameters?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn