Use of Go3 Points (...)

Keywords: Go PHP Java github

As we all know, the Go language is a strictly typed language, and when it is developed, it encounters uncertain input parameters. What should we do?

The three points here (...) give us great flexibility for programmers, as follows

Variable Quantity Parameters of Functions

May refer to https://github.com/guyan0319/...

Example

package main

import "fmt"

func main() {
    //MultParam can accept a variable number of parameters
    multiParam("jerry", "herry")
    names := []string{"jerry", "herry"}
    multiParam(names...)
}
func multiParam(args ...string) {
    //The accepted parameters are placed in the args array
    for _, e := range args {
        fmt.Println(e)
    }
}

It should be noted that the variable parameters are the right-most parameters of the function. Ordinary parameters are placed on the left, and can be 0 to n. as

package main

import "fmt"

func main() {
   //MultParam can accept a variable number of parameters
   multiParam("jerry", 1)
   multiParam("php", 1, 2)
}
func multiParam(name string, args ...int) {
   fmt.Println(name)
   //The accepted parameters are placed in the args array
   for _, e := range args {
      fmt.Println(e)
   }
}

Parameters of Variable Functions

If the slice is decompressed with the s... Symbol, the slice can be passed directly to the variable parameter function. In this case, no new slices are created.

Example

package main

import "fmt"

func main() {
    //MultParam can accept a variable number of parameters
    names := []string{"jerry", "herry"}
    multiParam(names...)
}
func multiParam(args ...string) {
    //The accepted parameters are placed in the args array
    for _, e := range args {
        fmt.Println(e)
    }
}

Another scenario is to merge two slice s through append.

    stooges := []string{"Moe", "Larry", "Curly"}
    lang := []string{"php", "golang", "java"}
    stooges = append(stooges, lang...)
    fmt.Println(stooges)//[Moe Larry Curly php golang java]

Array literal

In Array Text, the length specified by the... Symbol is equal to the number of elements in the text.

    stooges := [...]string{"Moe", "Larry", "Curly"}
    arr := [...]int{1, 2, 3}
    fmt.Println(len(stooges))
    fmt.Println(len(arr))

Here... can also not be used.

go command

go When describing a list of packages, the command uses three points as wildcards.

This command tests all packages in the current directory and its subdirectories.

$ go test ./...

Reference resources:

https://yourbasic.org/golang/...

links

Posted by Hatchmo on Thu, 10 Oct 2019 07:56:42 -0700