Indefinite parameters means that the number of parameters passed in by the function is an indefinite number; the indefinite parameter declaration uses the syntax format of "param...type". Characteristics of indefinite parameters: 1. All indefinite parameter types must be the same; 2. The indefinite parameter must be the last parameter of the function; 3. The indefinite parameter is equivalent to a slice in the function body, and the operation of the slice is also suitable for the indefinite parameter operation; 4. Slices can be passed as parameters to indefinite parameters, and "..." must be added after the slice name; 5. The types of functions whose formal parameters are indefinite parameters are different from those of functions whose formal parameters are slices.
The operating environment of this tutorial: Windows 7 system, GO version 1.18, Dell G3 computer.
What are indefinite parameters
Indefinite parameters mean that the number of parameters passed in by the function is an indefinite number.
package main import ( "fmt" ) /* 不定参数函数 */ func Add(a int, args ...int) (result int) { result += a for _, arg := range args { result += arg } return } func main() { fmt.Println(Add(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)) }
The Go function supports an indefinite number of formal parameters. The indefinite parameter declaration uses the syntax format of param...type
The indefinite parameters have the following characteristics:
①All variable parameter types must be the same.
②The indefinite parameter must be the last parameter of the function.
③The indefinite parameter is equivalent to a slice in the function body, and the operation of the slice is also suitable for the operation of the indefinite parameter.
④ Slices can also be passed as parameters to indefinite parameters, and "
...
" must be added after the slice name.
package main import "fmt" func Add(arr ...int) int { var count int arr1 := arr[1:] for _, val := range arr1 { count += val } return count } func main() { slice := []int{1, 2, 3, 4, 5} //array := [...]int{1, 2, 3, 4} fmt.Println(Add(slice...)) //fmt.Println(Add(array...)) //cannot use array (variable of type [4]int) as parameter of type []int }
⑤The types of functions whose formal parameters are indefinite parameters are different from those of functions whose formal parameters are slices.
package main import "fmt" func Add1(arr ...int) int { return arr[0] } func Add2(arr []int) int { return arr[0] } func main() { fmt.Printf("%T\n", Add1) fmt.Printf("%T\n", Add2) }
Passing of indefinite parameters
func SetData(args ...int) (result int) { //不定参数的传递 return Add(1, args...) } func main() { fmt.Println(SetData(1, 2, 3))//输出7 array := []int{1, 2, 3, 4} fmt.Println(Add(1, array...))//输出11 }
Any type of indefinite parameters
/* 任意类型的不定参数,用interface{}表示 */ func MyPrintf(args ...interface{}) { for _, arg := range args { //迭代不定参数 switch arg.(type) { case int: fmt.Println(arg, "is int") case string: fmt.Println(arg, "is string") case float64: fmt.Println(arg, "is float64") case bool: fmt.Println(arg, " is bool") default: fmt.Println("未知的类型") } } } func main() { /*输出结果: 12 is int haha is string 12.5 is float64 false is bool -12.5 is float64 */ MyPrintf(12, "haha", 12.5, false, -12.5) }
[Related recommendations: Go video tutorial, Programming teaching】
The above is the detailed content of What are indefinite parameters in go language?. For more information, please follow other related articles on the PHP Chinese website!

Go's strings package provides a variety of string manipulation functions. 1) Use strings.Contains to check substrings. 2) Use strings.Split to split the string into substring slices. 3) Merge strings through strings.Join. 4) Use strings.TrimSpace or strings.Trim to remove blanks or specified characters at the beginning and end of a string. 5) Replace all specified substrings with strings.ReplaceAll. 6) Use strings.HasPrefix or strings.HasSuffix to check the prefix or suffix of the string.

Using the Go language strings package can improve code quality. 1) Use strings.Join() to elegantly connect string arrays to avoid performance overhead. 2) Combine strings.Split() and strings.Contains() to process text and pay attention to case sensitivity issues. 3) Avoid abuse of strings.Replace() and consider using regular expressions for a large number of substitutions. 4) Use strings.Builder to improve the performance of frequently splicing strings.

Go's bytes package provides a variety of practical functions to handle byte slicing. 1.bytes.Contains is used to check whether the byte slice contains a specific sequence. 2.bytes.Split is used to split byte slices into smallerpieces. 3.bytes.Join is used to concatenate multiple byte slices into one. 4.bytes.TrimSpace is used to remove the front and back blanks of byte slices. 5.bytes.Equal is used to compare whether two byte slices are equal. 6.bytes.Index is used to find the starting index of sub-slices in largerslices.

Theencoding/binarypackageinGoisessentialbecauseitprovidesastandardizedwaytoreadandwritebinarydata,ensuringcross-platformcompatibilityandhandlingdifferentendianness.ItoffersfunctionslikeRead,Write,ReadUvarint,andWriteUvarintforprecisecontroloverbinary

ThebytespackageinGoiscrucialforhandlingbyteslicesandbuffers,offeringtoolsforefficientmemorymanagementanddatamanipulation.1)Itprovidesfunctionalitieslikecreatingbuffers,comparingslices,andsearching/replacingwithinslices.2)Forlargedatasets,usingbytes.N

You should care about the "strings" package in Go because it provides tools for handling text data, splicing from basic strings to advanced regular expression matching. 1) The "strings" package provides efficient string operations, such as Join functions used to splice strings to avoid performance problems. 2) It contains advanced functions, such as the ContainsAny function, to check whether a string contains a specific character set. 3) The Replace function is used to replace substrings in a string, and attention should be paid to the replacement order and case sensitivity. 4) The Split function can split strings according to the separator and is often used for regular expression processing. 5) Performance needs to be considered when using, such as

The"encoding/binary"packageinGoisessentialforhandlingbinarydata,offeringtoolsforreadingandwritingbinarydataefficiently.1)Itsupportsbothlittle-endianandbig-endianbyteorders,crucialforcross-systemcompatibility.2)Thepackageallowsworkingwithcus

Mastering the bytes package in Go can help improve the efficiency and elegance of your code. 1) The bytes package is crucial for parsing binary data, processing network protocols, and memory management. 2) Use bytes.Buffer to gradually build byte slices. 3) The bytes package provides the functions of searching, replacing and segmenting byte slices. 4) The bytes.Reader type is suitable for reading data from byte slices, especially in I/O operations. 5) The bytes package works in collaboration with Go's garbage collector, improving the efficiency of big data processing.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver CS6
Visual web development tools

Atom editor mac version download
The most popular open source editor

Dreamweaver Mac version
Visual web development tools
