SoFunction
Updated on 2025-03-05

Detailed explanation of the definition and use of functions for Go language learning

1. Function definition

The definition of the function is the same as Java, using {} for wrapping, and the parameter type and return type must be explicitly entered.

The sample code is as follows:

func min(num1, num2 int) int {
    if num1 <= num2 {
        return num1
    } else {
        return num2
    }
}
 
func main() {
    ("max = %d\n", min(10, 12))
}

Execution results

max = 10

2. Return multiple values

Like Python, multiple values ​​can be returned.

The sample code is as follows

func swap(num1, num2 int) (int, string) {
    return num1 + num2, "haha"
}
 
func main() {
    a, b := swap(10, 12)
    ("swap = %d - %v\n", a, b)
}

Execution results

swap = 22 - haha

3. Reference delivery

The reference address of the parameter can be passed to the function, so that the operation will affect the actual parameter.

The sample code is as follows

func swap1(num1, num2 *int) {
    var temp int
    temp = *num1
    *num1 = *num2
    *num2 = temp
}
 
 
func main() {
    c, d := 10, 20
    swap1(&c, &d)
    ("swap1 c=%d,d=%d\n", c, d)
}

Execution results

 swap1 c=20,d=10

4. Functions are used as real parameters

Like python, functions can be defined inside methods.

The sample code is as follows

func method(num1 int) int {
    getMax := func(x, y int) int {
        if x > y {
            return x
        } else {
            return y
        }
    }
    a := num1 - 10
    b := getMax(num1, a)
    ("value = %d\n", b)
    return b
}
 
func main() {
    ("method = %d\n", method(20))
}

Execution results

value = 20                         
method = 20

5. Anonymous functions

The function returns anonymous function and forms a closure.

The sample code is as follows

//Anonymous functionfunc anonymous(num int) func() int {
    var a int
    a = num
    return func() int {
        a += 1
        return a
    }
 
}
 
func main() {
    flagNum := anonymous(100)
    ("1 -&gt; %d\n", flagNum())
    ("2 -&gt; %d\n", flagNum())
    ("3 -&gt; %d\n", flagNum())
    flagNum1 := anonymous(18)
    ("4 -&gt; %d\n", flagNum1())
    ("5 -&gt; %d\n", flagNum1())
}

Execution results

1 -> 101                           
2 -> 102                           
3 -> 103                           
4 -> 19                            
5 -> 20

This is the article about the detailed explanation of the definition and use of functions in Go language learning. For more related Go language function content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!