Go function--a tutorial with the beginner of Go language

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed. Easy-to-understand Go function with diagram Tutorial! [] (https://raw.githubusercontent.com/studygolang/gctt-images/master/go-funcs/funcs.png) * * NOTE: * * This tutorial only describes the Go function, Does not include: variable parameters, delay functions, external functions, methods, HTTP, packet encoding, and so on. * * *### What is a function? A function is a separate block of code that can be reused and run again and again. The function can have an input parameter, or it can have a return value output. # # # Why do we need functions? -Increased readability, testability, and maintainability-so that different parts of the code can be executed separately-can be made up of a new module by a small module-you can add behavior to a type-easy to organize code-conforms to the [DRY principle] (https://en.wikipedia.org/wiki/Don%27t_ REPEAT_YOURSELF)! [] (https://raw.githubusercontent.com/studygolang/gctt-images/master/go-funcs/pLine.png)! [] (https://raw.githubusercontent.com/studygolang/gctt-images/master/go-funcs/1.png) declares a function "Len", the input parameter is "s", the type is " String ", the return value type is" int ". * * *####✪ First: Declare a len function ' Gofunc len (s string) int {return UTF8. Runecountinstring (s)} ' * * *####✪ then: Call it by its name ' Golen ("Hello World") ' [Online Run program] (https://play.golang.org/p/ 6C2P1YVCMY)! [] (Https://raw.githubusercontent.com/studygolang/gctt-images/master/go-funcs/pLine.png) # # # Input parameters and return value type input parameters are used to pass data to the function. The return value type is used to return data from the function. The data returned from the function is called the return value.! [] (Https://raw.githubusercontent.com/studyGolang/gctt-images/master/go-funcs/2.png) takes a String type "input parameter" named "S" and returns a return value with no name of "return value type" int.! [] (https://raw.githubusercontent.com/studygolang/gctt-images/master/go-funcs/pLine.png)! [] (https://raw.githubusercontent.com/studygolang/gctt-images/master/go-funcs/3.png) function signature is a [type of function] (https:// Golang.org/ref/spec#function_types)--consists of the input parameter type and the return value type. * * * ' gofunc jump ()//Signature: Func () func Len (s string) int//Signature: Func (String) IntFunc multiply (n ... float64) []float64//Signature: Fu NC (... float64) []float64 ' * * * *go the function in the language is a one-class citizen and can be passed by any assigned value. "' Goflen: = Lenflen (" hello! ") "[Running Program Online] (Https://play.golang.org/p/JgE1MoO-dP) A sample code for a function signature. [] (https://raw.githubusercontent.com/studygolang/gctt-images/master/go-funcs/pLine.png)! [] (https://raw.githubusercontent.com/studygolang/gctt-images/master/go-funcs/4.png) When a function is called, its body will run with the supplied input parameters. If the function declares at least one return value type, the function returns one or more return values. * * * You can return directly from the Runecountinstring function because it also returns an int. "' Gofunc Len (s string) int {return UTF8. Runecountinstring (s)}letterslen: = Len ("hey!") "* * * * This function uses[Expression] (https://golang.org/ref/spec#ExpressionList) as the return value. "' Gofunc returnwithexpression (A, b int) int {return a * b * 2 * ANOTHERFUNC (A, B)} '! [] (Https://raw.githubusercontent.com/studygolang/gctt-images/master/go-funcs/pLine.png) # # # function block Each set of parentheses creates a new function block, Any identifier declared within a function block is visible only within that function block. "' Goconst message =" Hello World "func HelloWorld () {Name: =" Dennis "message: =" Hello, earthling! "} "* * * * '" gohelloworld ()/*★message constants are visible here. ★ The variable inside the function name is not visible here. ★ A variable that is hidden inside a function message is not visible here. */"[Running Program Online] (https://play.golang.org/p/GBw0PbDw8p)! [] (Https://raw.githubusercontent.com/studygolang/gctt-images/master/go-funcs/pLine.png) Now, Let's look at how the input and return value types are declared in different styles. [] (https://raw.githubusercontent.com/studygolang/gctt-images/master/go-funcs/pLine.png)! [] (Https://raw.githubusercontent.com/studygolang/gctt-images/master/go-funcs/5.png) declares an input parameter "s" of type "String", And an integer return value type. [] (https://raw.githubusercontent.com/studygolang/gctt-images/master/go-funcs/pLine.png)! [] (https://raw.githubusercontent.com/studygolang/gctt-images/mAster/go-funcs/6.png) The input and return value types of a function work like a variable. [] (Https://raw.githubusercontent.com/studygolang/gctt-images/master/go-funcs/pLine.png) # # # Niladic function Niladic The function does not accept any input parameters. "' Gofunc tick () {FMT. Println (time. Now (). Format (time. Kitchen)}tick ()//output:13:50pm etc. "[Run Program Online] (HTTPS://PLAY.GOLANG.ORG/P/D6WNT0_MLQ) If a function does not return a value, you can omit the return value type and return this keyword.! [] (Https://raw.githubusercontent.com/studygolang/gctt-images/master/go-funcs/pLine.png) # # # Singular function "' Gofunc Square (n int) int {return n * N}square (4)//OUTPUT:16 "[Running Program Online] (https://play.golang.org/p/cJ2Q02_74h) When the function returns only one return value, Do not use parentheses. [] (Https://raw.githubusercontent.com/studygolang/gctt-images/master/go-funcs/pLine.png) # # # Multiple input parameters and return value ' ' ' Gofunc Scale (width, height, scale int) (int, int.) {return width * scale, Height * scale}w, h: = Scale (5, 2)//OUTPUT:W is 10 , H is 20 "[Online Running program] (HTTPS://PLAY.GOLANG.ORG/P/OULN6FZA92) Multiple return value types should be enclosed in parentheses. [] (Https://raw.githubusercontent.com/studygolang/gctt-images/master/go-funcs/pLine.png) # # # Automatic type assignment go language will be self-To the previous parameter declaration type. [] (https://raw.githubusercontent.com/studygolang/gctt-images/master/go-funcs/7.png) * * * These statements are the same: ' ' Gofunc scale ( width, height, scale int) (int, int.) func scale (width int, height int, scale int) (int, int) '! [] (Https://raw.githubusercontent.com/studygolang/gctt-images/master/go-funcs/pLine.png) # # # error value some functions [usually] (https:// Golang.org/doc/effective_go.html#multiple-returns) returns an error-Multiple return values make this easy to use. "' Gofunc write (w io. Writer, str string) (int, error) {return W.write ([]byte (s))]}write (OS. Stdout, "Hello")//Output:hello "* * * * * from the Write function directly return and return multiple return value types are the same. Because it also returns an int and an error value. "' Gofunc write (w io. Writer, str string) (int, error) {n, err: = W.write ([]byte (s)) return n, err} "" * * * if everything is OK, you can return nil as result: "' Gofunc div ( A, b float64) (float64, error) {if b = = 0 {return 0, errors. New ("Divide by Zero")}return A/b, nil}r, err: = div ( -1, 0)//Err:divide by zero "[Online Run program] (https://play.golang.org/p/7n -SCMRNY5)! [] (Https://raw.githubusercontent.com/studygolang/gctt-images/master/go-funcs/pLine. png) # # # Drop return value you can use an underscore to discard the return value. The go/* assumes that we have the following function: */func tempdir (dir, prefix string) (name string, err Error) ' * * * Discard Error return value (2nd return value): ' ' Goname, _: = Temp Dir ("", "Test") ' * * * Discard all return values: ' ' Gotempdir ("", "Test") '! [] (Https://raw.githubusercontent.com/studygolang/gctt-images/master/go-funcs/pLine.png) # # # omitted parameter name you can also use in unused input parameters , use the underscore as a name. --to satisfy an interface as an example (or [see here] (https://blog.cloudflare.com/quick-and-dirty-annotations-for-go-stack-traces/)). "' Gofunc Write (_ []byte) (n int, err error) {return 0, nil} '! [] (https://raw.githubusercontent.com/studygolang/gctt-images/master/go-funcs/pLine.png)! The [] (https://raw.githubusercontent.com/studygolang/gctt-images/master/go-funcs/8.png) named return value parameter allows you to use the return value as you would with a variable. And it allows you to use an empty return. * * * return value POS behaves like a variable, and the function biggest returns it with an empty return (there is no expression after return). "' go//biggest returns the subscript of the largest number in the slice nums. Func biggest (Nums []int) (pos int) {If len (nums) = = 0 {return-1}m: = Nums[0]for I, N: = range Nums {if n > m {m = NPOs = i}}//returns the Posreturn}pos: = Biggest ([]int{4,5,1})//Output:1 ' [Online Run Program] (Https://play.golang.org/p/B1_uRkia_I) above the program is not optimized, the time complexity of O (n). [] (Https://raw.githubusercontent.com/studygolang/gctt-images/master/go-funcs/pLine.png) # # # When should I use a named return value parameter? -The named return value parameter is primarily used as a hint for the return value. -Do not use the named return value parameter instead to skip the variable declaration inside the function. -If it makes your code more readable, please use it. * * * When you use the named return value parameter, there is also a [controversial] (https://news.ycombinator.com/item?id=14668323) optimization technique, but the compiler will soon fix the problem to prohibit its use. [] (Https://raw.githubusercontent.com/studygolang/gctt-images/master/go-funcs/pLine.png) # # # Caution Variable coverage problem ' ' Gofunc INCR (Snum String) (Rnum string, err error) {var i int//start of a new Scopeif I, err: = StrConv. Atoi (Snum); Err = = Nil {i = i + 1}//end of the new Scopernum = StrConv. Itoa (i) RETURN}INCR ("abc")//output:0 and Nil ' * * * * variables I and err are only visible within the if code block. Finally, the error should not be "nil", because "abc" cannot be converted to an integer, so this is an error, but we did not find this error. [Running programs online] (Https://play.golang.org/p/tx2Rmxn3nK) Click here to view the problem solution. [] (Https://raw.githubusercontent.com/studygolang/gctt-images/master/go-funcs/pLine.png) # # # VALUE transfer function pass Set the value of the input parameter to the corresponding 0 value. "' Gofunc Pass (s string, n int) {s, n = "", 0} "* * * * * We pass two variables to pass function:" ' gostr, num: = "Knuth", 2pass (str, num) ' * * * * function finished, our two variable value has no change. "Gostr is" Knuth "num is 2" * * This is because when we pass parameters to the function, the parameter is automatically copied a new variable. This is called value passing. [Running programs online] (Https://play.golang.org/p/maAz6FR-TA)! [] (Https://raw.githubusercontent.com/studygolang/gctt-images/master/go-funcs/pLine.png) # # # Value Pass and pointer below this function accepts a pointer to the A pointer to a string variable. It modifies the value that the pointer PS points to. It then attempts to set the value of the pointer to nil. Therefore, the pointer will no longer point to the address of the string variable passed in. "Gofunc Pass (PS *string) {*ps =" Donald "PS = nil}" * * * * We define a new variable s, then we use the & operator to get its memory address and save its memory address in a new pointer variable PS In "Gos: =" Knuth "PS: = &s" * * * Let's pass the PS to the pass function. "Gopass (PS)" After the function is finished, we will see that the value of the variable s has changed. However, the pointer PS still points to the valid address of the variable s. "' go//output://S:" Donald "//ps:0x1040c130" * * * The pointer PS is passed to the function pass by value, only the address it points to is copied to a new pointer variable (parameter) in the function pass. Therefore, setting the pointer variable to nil in the function has no effect on the pointer (argument) passed to the function. [] (https://raw.githubusercontent.com/studygolang/gctt-images/master/go-funcs/9.png) ' &s ' and ' ps ' are different variables, But they all point to the same variable ' s '. * * *[online Running program] (HTTPS://PLAY.GOLANG.ORG/P/YMAPKVFIDG)! [] (HTTPs://raw.githubusercontent.com/studygolang/gctt-images/master/go-funcs/pline.png) So far, we have learned how to declare the parameters of a function. Now, let's take a look at how to properly name functions, input parameters, and return value types. [] (Https://raw.githubusercontent.com/studygolang/gctt-images/master/go-funcs/pLine.png) # # # The benefits of function naming using functions include increased readability and maintainability of the code. You may need to take these comments according to the actual situation of choice. [] (Https://raw.githubusercontent.com/studygolang/gctt-images/master/go-funcs/pLine.png) # # # as short as possible when choosing the name as short as possible. Choose a short, self-describing and meaningful name. "' go//not this:func checkprotocolisfiletransferprotocol (protocoldata io. Reader) bool//this:func Detect (in IO. Reader) Name {return ftp}//not this:func createfromincomingjsonbytes (Incomingbytessource []byte)//This:func Newfromjson (src []byte) '! [] (Https://raw.githubusercontent.com/studygolang/gctt-images/master/go-funcs/pLine.png) # # # # # # # # using Hump nomenclature ' go//this: Func runserver () func runserver ()//Not This:func Run_server () func run_server () func runserver () ' ' * * * abbreviations should all be capitalized: ' ' go// Not This:func servehttp ()//This:func servehttp () "! [] (Https://raw.githubusercontent.com/studygolang/gctt-images/maSter/go-funcs/pline.png) # # # Select descriptive parameter name ' go//not This:func Encrypt (I1, A3, B2 byte) byte//This:func Encrypt (Privkey, pub Key, salt byte) byte//not This:func Write (Writablestream io. Writer, Bytestobewritten []byte]//This:func Write (w io. Writer, S []byte]//Type is very clear, there is no need to take the name of "!" [] (Https://raw.githubusercontent.com/studygolang/gctt-images/master/go-funcs/pLine.png) # # # Use the verb ' ' go//not this: Func MONGO (H string) error//This:func Connectmongo (host string) error//if this function is within the package MONGO, as long as this is OK: Func Connect (host Strin g) Error ""! [] (Https://raw.githubusercontent.com/studygolang/gctt-images/master/go-funcs/pLine.png) # # # use IS and is "go//not This:func pop (new bool) item//This:func pop (isnew bool) item '! [] (Https://raw.githubusercontent.com/studygolang/gctt-images/master/go-funcs/pLine.png) # # # does not need to be named with the type ' ' ' go// Not This:func Show (errorstring string)//This:func Show (Err string) '! [] (Https://raw.githubusercontent.com/studygolang/gctt-images/master/go-funcs/pLine.png) # # # Use Getters and setters in GThere are no Getters and Setters in the O language. However, you can simulate it by using a function. "' go//not This:func GetName () string//this:func name () string//not This:func name () string//this:func SetName (name St Ring) '! [] (Https://raw.githubusercontent.com/studygolang/gctt-images/master/go-funcs/pLine.png) # # # Go Features not supported by the function: Because I will explain some of the following issues in the upcoming articles, so you do not need to go to [DuckDuckGo] (https://duckduckgo.com/?q=does+golang+support+ FUNCTIONS&T=HG&IA=QA) or [Google] (https://www.google.com.tr/search?q=does+golang+support+functions) search for answers. -[function overloading] (https://golang.org/doc/faq#overloading)-it can be modeled by type assertions. -[Pattern Match function] (http://learnyouahaskell.com/syntax-in-functions). -The default parameter value in the function declaration. -Specify input parameters by name in any order in the declaration. [] (Https://raw.githubusercontent.com/studygolang/gctt-images/master/go-funcs/pLine.png) I hope you can share this article with your friends. Thank you!! [] (Https://raw.githubusercontent.com/studygolang/gctt-images/master/go-funcs/10.png)

via:https://blog.learngoprogramming.com/golang-funcs-params-named-result-values-types-pass-by-value-67f4374d9c0a

Author: inanc Gumus Translator: MDGSF proofreading: polaris1119

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

933 reads
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.