Golang function functions

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

Functional function

    • The GO function does not support nesting, overloading, and default parameters
    • However, the following features are supported:
    1. No need to declare prototypes
    2. Variable length parameter
    3. Multiple return values
    4. Named return value parameter
    5. anonymous functions
    6. Closed Package
    • The definition function uses the keyword func, and the opening brace cannot be another line
    • Functions can also be used as a type

return value and parameter description

func A(a int, b string) (int, string, int)  { //第一个小括号当中是你的参数列表,第二个小括号是你的返回值列表    }
func A(a, b, c int) (int, string, int)  {    //如果abc都是int型的话,可以按照这种方法进行简写,同样的方法也适用于返回值当中}
func A() (a, b, c int)  { //1:如果这样写的话就必须要命名返回值    //命名返回值和不命名返回值得区别}
func A() (int, int, int)  { //    //命名返回值和不命名返回值得区别    a, b, c := 1,2,3    return a,b,c    //如果此时没有命名返回值的时候,那么在返回值得时候就必须写上return a,b,c    //当然为了代码的可读性,这里我们规定必须return 的时候加上返回值名}

Indefinite Long variable parameter

package mainimport "fmt"func main()  {    A(1,2,3,4,5,6,7)}func A(a ...int) {    // 这里采用的是不定长变参,不定长变参必须是参数的最后一个参数,后面不能再跟 b string这样的参数    fmt.Println(a)}
package mainimport "fmt"func main()  {    s1:= []int{1,2,3,4}    a,b :=1,2    A(a,b)    fmt.Println(a,b)    B(s1)    fmt.Println(s1)}func A(a ...int) {    //这里传进来的实际上是一个slice,引用类型    a[0] = 3    a[1] = 4    //尽管我们在函数A当中接收到的是一个slice,但是它得到的是一个值拷贝    //和直接传递一个slice的区别看函数B    fmt.Println(a)}func B(s []int)  {    //这里并不是传递一个指针进去,而是对这个slice的内存地址进行了一个拷贝    //这里还可以看到像int型、string型进行常规的参数传进去的话,只是进行了个值拷贝,slice传进去虽然也是拷贝,但是它是内存地址的拷贝    s[0] = 4    s[1] = 5    s[2] = 6    s[3] = 7    fmt.Println(s)    //在这里 我们看到我们在函数B当中的修改,实际上影响到了我们main函数当中的变量s1    //如果直接传递一个slice,它的修改就会影响到这个slice的本身}PS:值类型和引用类型进行函数传参拷贝是不一样的,一个是拷贝值,一个是拷贝地址
package mainimport (    "fmt")func main() {    a := 1    A(&a) //这里取出a的地址    fmt.Println(a)}func A(a *int) { //传递的是指针类型    *a = 2 //在操作的时候需要去它的值进行操作,这个时候函数A就可以改变原始a的值    fmt.Println(*a)}

Use of function types

package mainimport (    "fmt")func main() {    a := A    a() //这个时候是将A的函数类型赋值给a,在go语言当中一切皆是类型啊}func A() {    fmt.Println("Func A")}

Use of anonymous functions

package mainimport (    "fmt")func main() {    a := func() {        //此时这个代码块就是一个匿名函数,这个函数本身没有名称,我们将她赋值给a,然后调用        fmt.Println("Func A")    }    a() //依然可以打印func A}

Closures in the Go language

package mainimport (    "fmt")func main() {    f := closure(10)    res1 := f(1)    fmt.Println(res1)    res2 := f(2)    fmt.Println(res2)}func closure(x int) func(int) int {    fmt.Printf("%p \n", &x)    return func(y int) int {        fmt.Printf("%p \n", &x)        return x + y    }}//这里可以看出3次打印x的地址都是一样的

Defer

    • Defer are executed in the same way as destructors in other languages, executed one after the other in the reverse order of the function execution
    • Even if the function has a critical error, it will execute
    • Calls that support anonymous functions
    • Typically used for operations such as resource cleanup, file closing, unlocking, and recording time
    • You can modify the function calculation result after return by cooperating with the anonymous function
    • If a variable in the function body is an argument to an anonymous function when defer, the copy is obtained when the defer is defined, or the address of a variable is referenced.

    • Go has no exception mechanism, but has panic/recove mode to handle errors
    • Panic can be thrown anywhere, but recover is only valid in functions called by defer

package mainimport (    "fmt")func main() {    fmt.Println("A")    defer fmt.Println("B")    defer fmt.Println("C")}//PS:打印的结果就是A C B
package mainimport (    "fmt")func main() {    for i := 0; i < 3; i++ {        //defer fmt.Println(i)        defer func() {            fmt.Println(i)        }() //调用这个函数    }}//刚才直接打印的时候,是作为一个参数传递进去,运行到defer的时候是将这个i的值进行了一个拷贝,所以打印的是 2 1 0//这种情况下i一直是一个地址的引用,i一直引用的是局部变量的i,在退出这个循环体的时候 i已经变成了3,在main函数return的时候,开始执行defer语句,defer语句的时候i已经变成了3

Exception mechanism

package mainimport (    "fmt")func main() {    A()    B()    C()}func A() {    fmt.Println("Func A")}func B() {    defer func() {        if err := recover(); err != nil {            fmt.Println("Recover in B")        }    }()    panic("Panic in B")}func C() {    fmt.Println("Func C")}
package mainimport (    "fmt")func main() {    var fs = [4]func(){}    for i := 0; i < 4; i++ {        defer fmt.Println("defer i=", i) //这个i是传递进来的参数,所以是值得拷贝        defer func() {            fmt.Println("defer_closure i=", i) //这里的i是引用外部的i,所以循环结束后,i变成了4        }()        fs[i] = func() {            fmt.Println("closure i = ", i) //这里也是引用外部的i,所以循环结束后i变成了4        }    }    for _, f := range fs {        f()    }}
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.