The function of Golang

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

function declaration

Grammar:

func name(parameter-list) (result-list) {    body}

If the function does not return a value, or if there is only an anonymous return value, then the result-list parentheses can be omitted, for example:

func sayHello() () {    fmt.Println("Hello, world!")}

Can be written as:

func sayHello() {    fmt.Println("Hello, world!")}

In addition to the anonymous return value (that is, given only the type of the return value, without the name), go also supports named return values, such as:

func max(x, y int) (z int) {    if x > y {       z = x    } else {       z = y    }    return}

In the above function, the return value is named, its name is "Z", and the return value is visible within the function. So we can manipulate the return value variable process in the function and return it directly using a return statement, when the function returns the value of the variable Z.

function variables

In Go, functions are class citizens, so like other types, functions have types, and they can be assigned to a variable, pass a function variable as one argument to another function, and even the function can be returned as a return value.
For example:

func add(x, y int) int {    return x + y}func doSomething(x, y int, f func(int, int) int) {    fmt.Println(f(x, y))}func main() {    f := add    fmt.Println(f(1, 2))    doSomething(10, 20, f)}

In the above example, we first assign the function add to the variable F, so it can be called directly with F as the function name.
We then passed the function variable f as a parameter to the DoSomething function and called it in DoSomething.
Where the dosomething parameter "f func (int, int) int" means to accept a function variable whose type is func (int, int) int, that is to accept a two int argument, and the return value is the Int class Type of function .

anonymous functions

对于命名函数来说, 它们必须要在包范围上定义, but we can use the function literal to define a function in any expression.
The syntax of a function literal is similar to a function declaration, but it has no function name. And a function literal is an expression, and the value of the expression is called an anonymous function .
With anonymous functions, we can implement closures:

func increment(x int) func() int {    return func () int {        x++        return x    }}func main() {    f := increment(10)    fmt.Println(f())    fmt.Println(f())    fmt.Println(f())    fmt.Println(f())}

The increment function above receives an int variable and then returns a function of type func () int . Notice that in the returned anonymous function, a local variable of increment is used, and each time the returned function is called, the value of x is increased by one.
From the above example, we see that a function is not just composed of code, it also has an internal state (in this case, the state of the function f is the value of x, it captures the external variable x, each time F is called, the value of x changes, so the state of f is changed). Because there is a hidden state in the internal maintenance of a function, we specify that a function type is a reference type, and that the function type is not comparable.
Like the anonymous function returned by the increment function above, if an anonymous function captures a local variable outside, then we call this anonymous function as a closure (closure)

Variable parameter function

A function is called a parameter function if it can receive a variable number of functions.
The parameter name and type of the last parameter of a variable parameter function need to be added ..., indicating that this argument is a variable, for example:

func oper(name string, vals ...int) {    total := 0    if (name == "add") {        for _, val := range vals {            total += val        }    } else {        for _, val := range vals {            total -= val        }    }    fmt.Printf("Operation %s, result: %d\n", name, total)    fmt.Printf("vals type: %T\n", vals)}func main() {    oper("add", 1, 2, 3, 4, 5)}

The first argument to the Oper function is a string, and the remaining argument is one or more int variables.
Go implements the argument function by assigning an array first, then copying the parameters to the array, and then passing the entire array's slices as parameters to the function.
So the above "oper" ("Add", 1, 2, 3, 4, 4) "calls can be equivalent to:

arr := []int{1, 2, 3, 4, 5}oper("add", arr[:]...)// 也可以直接传递数组oper("add", arr...)

不过上面的例子有一个需要特别注意的地方, 如果参数已经是 slice 的了, 那么调用变参函数时, 参数后需要添加**...**
虽然在函数内部, 变参是一个 slice, 但是变参函数和接收 slice 的函数是不同类型的.
For example:

func f(...int) {}func g([]int) {}func main() {    fmt.Printf("%T\n", f) // "func(...int)"    fmt.Printf("%T\n", g) // "func([]int)"}

About panic and recover

Panic is similar to an exception in Java, and generates a panic when a fatal error occurs while the program is running.
Of course we can also manually trigger a panic, for example:

func test() {    panic("some error")}

We directly invoke the built-in panic function to receive a panic, similar to the new Exception () in Java.
If a panic is produced, the program is usually terminated immediately. But sometimes we don't want the entire program to crash when panic occurs, and you can use the Recover function to capture this panic (the equivalent of Java's try ... catch). For example:

func test() {    defer func() {        if p := recover(); p != nil {            fmt.Printf("We got error: %v\n", p)        }    }()    panic("some error")}func main() {    test()    fmt.Println("OK")}

There are two points to note when using recover:

    • The recover call must be in the defer function.
    • The defer function requirements for parcel recover are called before the potential panic code.

For example:

func test() {    panic("some error")        defer func() {        if p := recover(); p != nil {            fmt.Printf("We got error: %v\n", p)        }    }() }

The above code directly causes the program to crash without triggering the recover.

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.