Functions

func plus(a int, b int) int {
    return a + b
}

func plusPlus(a,  b, c int) int {
    return a + b + c
}

func main() {
    res := plus(1, 2)
    fmt.Println("1+2 =", res)
    
    res = plusPlus(1, 2, 3)
    fmt.Println("1+2+3 =", res)
}
  • Go requires explicit returns, it won't automatically return the value of the last expression.

Multiple Return Values

//The (int, int) in this fuction signature shows that the function returns 2 ints.
func vals() (int, int) {
    return 3, 7
}

func main() {

    //Here we use the 2 different return values from the call with multiple assignment.
    a, b := vals()
    fmt.Println(a)
    fmt.Println(b)
    
    //하나의 값만 원한다면 _ 이 blank identifier를 이용해라.
    _, c := vals()
    fmt.Println(c)
}

Variadic Functions

  • Variadic functions can be called with any number of trailing arguments

  • For example, fmt.Println() is a common variadic function

func sum(nums ...int) {
    fmt.Print(nums, " ")
    total := 0
    
    //index, values = _, num
    for _, num := range nums {
        total += num
    }
    fmt.Println(total)
}

func main() {
    sum(1, 2)
    sum(1, 2, 3)
    
    nums := []int{1, 2, 3, 4}
    sum(nums...)
}

Closures

  • Go supports anonymous functions, which can form closures

  • It is useful when you want to define a function inline without having to name it.


func intSeq() func() int {
    i := 0
    return func() int {
        i++
        return i
    }
}
func main() {
    nextInt := intSeq()
    
    fmt.Println(nextInt()) // 1
    fmt.Println(nextInt()) // 2
    fmt.Println(nextInt()) // 3
    
    newInts := intSeq()
    fmt.Println(newInts()) // 1
}
  • Function intSeq returns another function, which we define anonymously in the body of intSeq

  • The return function closes over the variable i to form a closure

Last updated