📜  如何在 Golang 中使用省略号 (…)?

📅  最后修改于: 2021-10-25 02:10:52             🧑  作者: Mango

Golang 中的三个点 ( ) 在 Golang 中称为省略号,用于可变参数函数。使用不同数量的参数调用的函数称为可变参数函数。或者换句话说,允许用户在可变参数函数传递零个或多个参数。 fmt.Printf 是可变参数函数的例子,它在开始时需要一个固定参数,然后它可以接受任意数量的参数。

可变参数函数的最后一个参数总是使用省略号。这意味着它可以接受任意数量的参数。

示例 1:

Go
// Golang program to show
// how to use Ellipsis (…)
package main
  
import "fmt"
  
func main() {
    sayHello()
    sayHello("Rahul")
    sayHello("Mohit", "Rahul", "Rohit", "Johny")
}
  
// using Ellipsis
func sayHello(names ...string) {
    for _, n := range names {
        fmt.Printf("Hello %s\n", n)
    }
}


Go
// Golang program to show
// how to use Ellipsis (…)
package main
 
import (
    "fmt"
)
 
// using a variadic function
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() {
 
    // calling the function with
    // variable number of arguments
    find(89, 89, 90, 95)
    find(45, 56, 67, 45, 90, 109)
    find(78, 38, 56, 98)
    find(87)
}


输出:

Hello Rahul
Hello Mohit
Hello Rahul
Hello Rohit
Hello Johny

示例 2:

// Golang program to show
// how to use Ellipsis (…)
package main
 
import (
    "fmt"
)
 
// using a variadic function
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() {
 
    // calling the function with
    // variable number of arguments
    find(89, 89, 90, 95)
    find(45, 56, 67, 45, 90, 109)
    find(78, 38, 56, 98)
    find(87)
}

输出:

type of nums is []int
89 found at index 0 in [89 90 95]

type of nums is []int
45 found at index 2 in [56 67 45 90 109]

type of nums is []int
78 not found in  [38 56 98]

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