First, the format of the Go language function
Function constitutes the logical structure of the code is executed, the Go language, the basic function of the composition: Keyword func, function name, parameter list, the return value of the function body and return statements, each program contains a number of functions, function is the basic building blocks.
// no return value of the function FUNC log (Message String ) { } // return a value of the function FUNC the Add (A, B int ) int { return var1 } // a plurality of return value of the function FUNC Power (name String ) ( int , BOOL ) { return var1, var2 } // to the return named FUNC the Add (A, B int ) (C int ) { c = a + b return c }
Returns the value of the multi-function
func main() { a := 0 b := 0 a, b = addAndMultiply(10, 20) fmt.Println("a=", a) fmt.Println("b=", b) } func addAndMultiply(a, b int) (int, int) { return a + b, a * b }
Second, as a function of the parameter
package main import "fmt" import "strings" func main() { str := strToCase("ABDCFSDFE", processLetter) fmt.Println(str) } // function arguments FUNC strToCase (STR String , myfunc FUNC ( String ) String ) String { return myfunc (STR) } // string alternating parity FUNC processLetter (STR String ) (Result String ) { for I, value: = Range STR { IF I% 2 == 0 { result += strings.ToUpper(string(value)) } else { result += strings.ToLower(string(value)) } } return result }
Use type Custom type
package main import "fmt" import "strings" func main() { str := strToCase("ABDCFSDFE", processLetter) fmt.Println(str) } // function arguments (parameter type defined using type) FUNC strToCase (STR String , myfunc processLetterFunc) String { return myfunc (STR) } // use the type of processLetter () function defines the type of type processLetterFunc FUNC ( String ) String // string alternating parity FUNC processLetter (STR String ) (Result String ) { for I, value: = Range STR { IF I% 2 == 0 { result += strings.ToUpper(string(value)) } else { result += strings.ToLower(string(value)) } } return result }
Second, the scope of variables
1, when a local variable with the same name and global variables, local variables priority
// global variable var NUM int = 100 var num2 int = 200 is func main() { Surely, num2: = 1 , 2 fmt.Println ( " num = " , num) // num = 1 fmt.Println("num2=", num2)// num2=2 }