This is a creation in Article, where the information may have evolved or changed.
This article is reproduced, original: Golang study notes (2)--function
function definition
函数Is the most basic part of every development language, let's look at how the functions in the Go language are defined:
func Add(a, b int)int{ return a + b}
funcIs the keyword that defines the function, Add is the function name, int is the return value, and the parentheses are the parameters of the function. You can arrange the order of function definitions at will, and go scans the files at compile time.
Multiple return values
The GO function supports multiple return values and can return any number of return values. Multivalued returns are often used in the go language, for example, when a function returns both results and exceptions.
Let's look at an example where the divide function is to calculate the result of A/b and return the quotient and remainder.
package mainimport "fmt"func main(){ quotient, remainder := divide(5, 3) fmt.Println("商为:", quotient, "余数为:", remainder)}func divide(a, b int)(int, int){ quotient := a / b remainder := a % b return quotient, remainder}
Variable parameter function
Functions in Go support variable arguments, which means that functions can have any number of arguments. The argument is essentially one and slice must be 最后一个参数 . slicewhen passing to a variable parameter function, be careful to ... expand it, or treat it as a single parameter.
Take a look at the following example:
package mainimport "fmt"func main(){ result := sum(3,5,7,9) fmt.Println("结果为:", result)}func sum(aregs ...int) int { s := 0 for _, number := range aregs{ s += number } return s}
As for what is
slice,
rangeWhat the hell, in the back of the array of arrays when the detailed description,
sliceis equivalent to an array,
rangeLike a loop, loop through each word element of key, value. The other One
_Indicates that the return value is not accepted.
Defer
Defer is unique to the go language, and the function of defer is 延迟执行 to 后进先出 execute each defer registered functions one time before the function returns, in the form of a stack. This ensures that the function is called before it is returned, and is often used for resource release, error handling, cleanup of data, and so on. Here is an example of a read file.
package mainimport "fmt"import "os"func main(){ str, err := readFile("main.go") if err != nil{ fmt.Println(err.Error()) return } fmt.Println(str)}func readFile(strFileName string)(string, error){ f, err := os.Open(strFileName) if err != nil{ fmt.Println("文件读取失败") return "", err } defer f.Close() buf := make([]byte, 1024) var strContent string = "" for{ n, _ := f.Read(buf) if n == 0{ break } strContent += string(buf[0:n]) } return strContent, nil}
function type
A function is also a type, a function that has the same parameters, the same return value, and is the same type. Used type to define the function type. In the example below, display the function outputs a value greater than 5.
package mainimport "fmt"type MyFuncType func(int) boolfunc isBigThan5(n int)bool{ return n > 5}func display(arr []int, f MyFuncType){ for _, v := range arr{ if f(v){ fmt.Println(v) } }}func main(){ arr := []int{1,2,3,4,5,6,7,8,9} display(arr, isBigThan5)}
In the example above,
type MyFuncType func(int) boolDefines a function type that is named
MyFuncType, takes an argument of type int and returns the result of a type bool.
isBigThan5Is
MyFuncTypeType of function, function type. Like a function pointer in C, he can pass a function as a parameter into another function, and it's kind of like a delegate.
Error handling
There is no try...catch...finally... such structured exception handling in the go language, but instead of panic throw running out of exception. Use recover functions to catch exceptions. Recoveronly used in a defer function to catch an exception, the execution of the function has been interrupted and cannot be resumed to a subsequent location to continue execution.
package mainimport "fmt"func main(){ test()}func test(){ defer func (){ if err := recover(); err != nil{ fmt.Println(err) } }() divide(5,0) fmt.Println("end of test")}func divide(a, b int) int{ return a / b}
Finish
This article is original, reproduced please indicate the source
Previous section: Golang Study Notes (1)--Basics