What is the difference between []string and …string in golang?

前端 未结 4 495
醉话见心
醉话见心 2021-01-30 09:44

In the Go language,

[]string is a string array

and we also use ...string as a parameter.

What is the difference?

Functi

4条回答
  •  一向
    一向 (楼主)
    2021-01-30 10:39

    It simplifies your function parameters. Here is an example(https://play.golang.org/p/euMuy6IvaM): Method SampleEllipsis accepts from zero to many parameters of the same type but in the method SampleArray it is mandatory args to be declared.

    package main
    
    import "fmt"
    
    func SampleEllipsis(args ...string) {
        fmt.Printf("Sample ellipsis : %+v\n",args)
    }
    
    
    func SampleArray(args []string) {
        fmt.Println("Sample array ")
        SampleEllipsis(args...)
    }
    
    func main() {
        // Method one
        SampleEllipsis([]string{"A", "B", "C"}...)
        // Method two
        SampleEllipsis("A", "B", "C")
        // Method three
        SampleEllipsis()
    
        // Simple array
        SampleArray([]string{"A", "B", "C"})
    
        // Simple array
        SampleArray([]string{})
    
    }
    

    Returns :

    Sample ellipsis : [A B C]
    Sample ellipsis : [A B C]
    Sample ellipsis : []
    Sample array 
    Sample ellipsis : [A B C]
    Sample array 
    Sample ellipsis : []
    

提交回复
热议问题