go function learning notes

What is a function

Code block with input and output to perform specific functions

func functionnname([partmeternam type]) [return type] {
  // function body
}


Several types of functions


  • Function with no parameter return value

  • Function with parameter return value

  • defer statement


1. Function with no parameter return value


package main
import "fmt"


func functiontest1(a,b int) int  {
    return a + b 
    //Output 15
}

func main()  {
    sum1 :=functiontest1(12,3)
    fmt.Println(sum1)
}

2. Function with parameter return value

Multiple return values


package main
import "fmt"

func functiontest2(a,b int) (int,int) {
    sum := a + b 
    sub := a - b
    return sum,sub
}

func main()  {
    sum,sub := functiontest2(13,4)
    fmt.Printf("sum=%d\n sub=%d",sum,sub)
    //Output
    sum=17
    sub=9
}


Name the return value

package main
import "fmt"

func functiontest3(a,b int) (sum int,sub int) {
    sum = a + b 
    sub = a - b
    return 
}

func main()  {
  
    sum,sub := functiontest3(30,40)
    fmt.Printf("sum=%d\n sub=%d",sum,sub)
    //Output
  sum=70
  sub=-10

}

If the identifier does not need to be output, it can be represented by

package main
import "fmt"

func functiontest4(a,b int) (sum int,sub int) {
    sum = a + b 
    sub = a - b
    return 
    
}

func main()  {
   sum,_ := functiontest4(21,10)
    fmt.Printf("sum=%d",sum)
    //Output
    sum=31    
}


Variable parameter 1, passing array args

func functiontest5(a...int) (sum int)  {

    for i := 0; i < len(a); i++ {
        sum =sum + a[i]
    }
    fmt.Println(sum)
    return sum
    
}

func main()  {

functiontest5(11,12,9)
//Output 32

}


Variable parameter 2

package main
import "fmt"

func functiontest6(a int, b ...int) (sum int, sub int) {
    s1 := 0
    for i := 0; i < len(b); i++ {
        s1 = s1 + b[i]
    }
    sum = s1 + a 
    sub = s1 - a 
    return sum,sub
}

func main()  {
sum,sub := functiontest6(1,2,311,4)
fmt.Println(sum,sub)
//Output
318 316
}
  • defer 

Function of defer: in functions, programmers often need to create resources (such as database connection, file handle, lock, etc.), in order to release resources in time after function execution, the designer of Go provides defer (delay mechanism).


Single defer in and out

package main
import "fmt"

func defer_test1(a int ,b...int) (sum int,sub int) {
    defer fmt.Println("deffer")
   for i := 0; i < len(b); i++ {
       fmt.Println(b[i])
   }
  return
}

func main()  {

defer_test1(1,123,23,45,6)
//Output
123
23
45
6
deffer
}

Multiple deffer

func defer_test1(a int ,b...int) (sum int,sub int) {
    defer fmt.Println("deffer1")
    defer fmt.Println("deffer2")
    defer fmt.Println("deffer3")
   for i := 0; i < len(b); i++ {
       fmt.Println(b[i])
   }
  return
}

func main()  {

defer_test1(1,123,23,45,6)
//Output
123
23
45
6
deffer3
deffer2
deffer1

}






Tags: Go Database

Posted on Fri, 17 Apr 2020 07:11:22 -0700 by 00Sven