This is a creation in Article, where the information may have evolved or changed.
function definition
type mytype int // 新的类型func (p mytype) funcname(q int) (r,s int) {return 0,0}
Scope
In Go, variables defined outside the function are global, and variables defined inside the function are local to the function. If the name overrides-a local variable has the same name as a global variable-the local variable overrides the global variable when the function executes.
Multi-value return
func (file *File) Write(b []byte) (n int, err error)
Go function can return multiple values
Named return value
The return value or result parameter of the Go function can specify a name and be used as the original variable, just like the input parameter. If they are named, they are initialized with the 0 value of their type at the beginning of the function. If the function executes the return statement without arguments, the result parameter is returned.
Cases:
func ReadFull(r Reader, buf []byte) (n int, err error) { for len(buf) > 0 && err == nil { var nr int nr, err = r.Read(buf) n += nr buf = buf[nr:len(buf)] } return }
Delay Code Defer
The function specified after defer is called before the function exits.
func ReadWrite() bool { file.Open("file") defer file.Close() // file.Close()被添加到了defer列表 if failureX { return false } if failureY { return false } return true}
You can put multiple functions into the delay list, for example:
for i:=0; i<5; i++ {defer fmt.Printf("%d ", i)}// 延迟的函数是按照后进先出(LIFO)的顺序执行,所以上面的代码打印:4 3 2 1 0。
Using defer can even modify the return value, assuming that named result parameters and function symbols are being used.
defer func() {/* ... */}() // ()在这里是必须的
Or This example, it's easier to understand why, and where to look for parentheses:
defer func(x int) { /* ... */}(5) // 为输入参数 x 赋值 5
In this (anonymous) function, you can access any of the named return parameters:
func f() (ret int) { //ret初始化为零 defer func() { ret++ //ret增加为1 }() return 0 // 返回的是1而不是0}
Variable parameter
A function that accepts an indefinite number of arguments is called a variable parameter function. Define the function to accept the arguments:
func myfunc(arg ...int) { }
Arg ... int tells Go that the function accepts an indefinite number of arguments. Note that the types of these parameters are all int.
In the function body, the variable arg is an int of type slice:
for _, n := range arg { fmt.Printf("And the number is: %d\n", n)}
If you do not specify the type of the parameter, the default is an empty interface interface{} (see Chapter 5th). Suppose there is another
A variable parameter function is called MYFUNC2, and the following example shows how to pass a parameter to it:
func myfunc(arg ...int) { myfunc2(arg...) ← 按原样传递 myfunc2(arg[:2]...) ← 传递部分}
function as a value
Functions in Go are also values, and functions can assign values to variables:
func main() { a := func() { // 定义一个匿名函数,并赋值给a println("Hello") } a() // 调用函数}
Callback
Because the function is also a value, it can be easily passed to other functions, and then it can be used as a callback.
func printit(x int) { // 函数无返回值 fmt.Printf("%v\n", x) // 仅仅打印}func callback(y int, f func(int)) { // f 将会保存函数 f(y) // 调用回调函数 f 输入变量 y}
Panic (Panic) and recovery (Recover)
Panic: is a built-in function that interrupts the original control flow and enters a scary process. When function f calls panic, the execution of the function f is interrupted, and the delay function in F executes normally, and then F returns to the place where it was called. Where the call is made, the behavior of F is like calling panic. This process continues up until all goroutine are returned when the program crashes.
Panic can be directly called panic generation. It can also be generated by a run-time error, such as an array that accesses out of bounds.
Recover: is a built-in function that allows Goroutine to recover from a panic-entering process. The recover is only valid in the delay function.
During normal execution, the call to recover returns nil and has no other effect. If the goroutine in the current period is in panic, the call recover can capture the input value of panic and return to normal execution.
Cases:
这个函数检查作为其参数的函数在执行时是否会产生 panic c: . func throwsPanic(f func()) (b bool) {//定义一个新函数 throwsPanic 接受一个函数作为参数(参看 “函数作为值”)。函 数 f 产生 panic,就返回 true,否则返回 false; defer func() { //定义了一个利用 recover 的 defer 函数。如果当前的 goroutine 产生了 panic,这个 defer 函数能够发现。当 recover() 返回非 nil 值,设置 b 为 true; if x := recover(); x != nil { b = true } }() f() // 调用作为参数接收的函数。 return // 返回 b 的值。由于 b 是命名返回值,无须指定 b。}