Go Series Tutorial--12. Variable parameter functions

Source: Internet
Author: User
Tags variadic
This is a creation in Article, where the information may have evolved or changed. Welcome to the 12th chapter of [Golang Series Tutorial] (/SUBJECT/2). # # What is a variadic function variable parameter function is a variable number of parameters function. # # syntax If the last parameter of a function is written as ' ... T ', then the function can accept any of the ' T ' type parameters as the last parameter. Note that only the last parameter of the function is allowed to be mutable. # # Some examples to understand how variadic functions work do you ever wonder how the Append function adds any parameter values to the slice. This allows the APPEND function to accept a different number of parameters. "' Gofunc append (slice []type, Elems ... Type) []type ' above is the definition of the APPEND function. Elems is a mutable parameter in the definition. This allows the APPEND function to accept variable parameters. Let's create our own variable parameter function. We will write a simple program to find out if an integer exists in the input integer list. "' Gopackage mainimport (" FMT ") func find (num int, nums ... int) {FMT. Printf ("Type of Nums is%t\n", nums) Found: = FalseFor 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 () {Find (*,,,,,,,) find (*, (), "109,") Find (87)} ' [Online Run code] (https: play.golang.org/p/7occymis6s) in the above program ' func find (num int, nums ... int) ', ' nums ' can accept any number of arguments. In the Find function, the parameter ' nums ' is equivalent to an integer slice. * * The Variadic function works by converting a variable parameter to a new slice. With the 22nd behavior in the above procedure, the variable parameter in the ' Find ' function is 89,90,95. The Find function accepts a variable argument of type ' int '. So these three parameters are converted by the compiler to an int type slice ' int []int{89, 90, 95} ' and then passed into the ' find ' function. * * In line 10th, ' for ' loops through the ' nums ' slice, if ' num ' is in the slice, the position of ' num ' is printed. If ' num ' is not in the slice, the print prompt does not find the number. The output value of the above code is as follows, "' type of nums is []int89 found at index 0 in [56] 95]type of the nums is []int45 found at index 2 in [67 45 109]type of Nums is []int78 not found in [98]type of Nums ' []int87 ' found in [] ' on line 25th of the above program, the Find function has only one parameter 。 We did not pass any parameters to the variable parameter ' nums ... int '. This is also legal, in this case ' nums ' is a length and capacity of 0 ' nil ' slices. # # to pass a variable parameter function into a slice in the example below, we pass a slice to the variadic function to see what happens. "' Gopackage mainimport (" FMT ") func find (num int, nums ... int) {FMT. Printf ("Type of Nums is%t\n", nums) Found: = FalseFor 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 () {nums: = []int{89, 95}find (nums)} ' [Online Run code] (https://play.golang.org/p/7occymiS6s) in In 23 rows, we pass a slice to a variadic function. In this case, the compiler could not compile the error ' MAIN.GO:23:CAnnot use Nums (Type []int) as type int in argument to find '. Why can't we work? The reason is straightforward, the ' find ' function is described as follows, "' Gofunc find (num int, nums ... int) ' is defined by a variadic function, ' nums ... int ' means that it can accept variable arguments of type ' int '. In line 23rd of the above program, ' Nums ' is passed in as a mutable parameter to the ' Find ' function. As we know earlier, these variadic parameters are converted to ' int ' type slices and then passed into the ' find ' function. But here ' nums ' is already an int-type slice, and the compiler tries to create a slice on the ' nums ' basis, like this ' Gofind ([]int{nums}) ', ' This fails because ' nums ' is a ' []int ' type and Not an ' int ' type. So is there a way to pass in the slice parameter to the Variadic function? The answer is yes. * * There is a syntax sugar that can be passed directly to a variable parameter function, and you can add a ' ... ' suffix after slicing. If you do this, the slice will pass directly to the function and no new tiles are created * * in the program above, if you replace the 23rd line of ' Find (nums) ' with ' Find (nums ...) '. ', the program will compile successfully and have the following output ' Gotype of nums is []int89 found at index 0 in [89 90 95] ' ' Below is the complete program for your reference. "' Gopackage mainimport (" FMT ") func find (num int, nums ... int) {FMT. Printf ("Type of Nums is%t\n", nums) Found: = FalseFor 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 () {nums: = []int{89, Nums, 95}find (...)} "[Run online]Code] (https://play.golang.org/p/7occymiS6s) # # No visual error when you modify a slice in a variadic function, make sure you know what you're doing. Let's look at a simple example below. "Gopackage mainimport (" FMT ") func change (S ... string) {s[0] =" Go "}func main () {welcome: = []string{" Hello "," World "}ch Ange (Welcome ...) Fmt. PRINTLN (Welcome)} "[Online Run Code] (https://play.golang.org/p/7occymiS6s) What do you think this code will output? If you think it outputs ' [Go World] '. Congratulations to you! You have already understood variadic functions and slices. If you're wrong, it doesn't matter, let me explain why there is such an output. In line 13th, we used the syntax sugar ' ... ' and passed the slice as a mutable parameter to the ' Change ' function. As we discussed earlier, if you use ' ... ', the ' welcome ' slice itself is passed directly as a parameter, and no new slices need to be created. This parameter ' welcome ' is passed as a parameter to the ' change ' function in the ' changing ' function, the first element of the slice is replaced with ' Go ', and the program produces the following output value ' [Go world] ' here is an example to understand the Variadic function. "Gopackage mainimport (" FMT ") func change (S ... string) {s[0] =" Go "s = Append (S," playground ") fmt. Println (s)}func main () {welcome: = []string{"Hello", "World"}change (Welcome ...) Fmt. PRINTLN (Welcome)} "[Online Run Code] (https://play.golang.org/p/7occymiS6s) I will leave it as an exercise for you, please point out how the above program is running:). The above is an introduction to variable parameter functions. Thanks for reading. You are welcome to leave valuable feedback and comments. I wish you a happy life. * * Previous Tutorial-[Array and Slice] (https://studygolang.com/articles/12121) * * * * Next tutorial-[Maps] (https://studygolang.com/articles/12251) * *

via:https://golangbot.com/variadic-functions/

Author: Nick Coghlan Translator: Fengchunsgit proofreading: Noluye

This article by GCTT original compilation, go language Chinese network honor launches

This article was originally translated by GCTT and the Go Language Chinese network. Also want to join the ranks of translators, for open source to do some of their own contribution? Welcome to join Gctt!
Translation work and translations are published only for the purpose of learning and communication, translation work in accordance with the provisions of the CC-BY-NC-SA agreement, if our work has violated your interests, please contact us promptly.
Welcome to the CC-BY-NC-SA agreement, please mark and keep the original/translation link and author/translator information in the text.
The article only represents the author's knowledge and views, if there are different points of view, please line up downstairs to spit groove

3,473 reads ∙1 likes
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.