In Go language (Golang), functions are basic code organization units, mainly used to encapsulate a piece of code, making the code structure clearer and reusable. The following will introduce the basic usage of functions in Go language, parameter passing, return value, multiple return value, anonymous functions, recursion and defer statements.
1. Basic function definition and call
In Go, the basic definition format of a function is as follows:
func Function name(Parameter list) Return value type { // Function body}
-
func
Keywords are used to define functions. -
Function name
It is the identifier of the function, and the initial letter can be exported. -
Parameter list
Contains parameter names and parameter types, and multiple parameters are separated by commas. -
Return value type
Optional, if the function does not return a value, it can be omitted.
Example:
package main import "fmt" // Define a simple addition functionfunc add(a int, b int) int { return a + b } func main() { result := add(3, 5) ("3 + 5 =", result) }
2. Multiple return values
Go language supports multiple return values, which can be used to return multiple results, such as success or failure flags and result values.
Example:
func divide(a, b float64) (float64, error) { if b == 0 { return 0, ("The divisor cannot be 0") } return a / b, nil } func main() { result, err := divide(10, 2) if err != nil { ("Error:", err) } else { ("10 / 2 =", result) } }
3. Name the return value
When defining a function, you can name the return value, so that the value can be assigned directly to the return variable within the function, and finally usereturn
Just return, without explicitly writing the return variable.
Example:
func rectangle(width, height float64) (area, perimeter float64) { area = width * height perimeter = 2 * (width + height) return }
4. Parameter passing
Parameter transfer in Go is divided intoValue passandReference pass:
- Value pass: By default, all parameters are passed by values, that is, it is a copy of the parameters passed.
- Reference pass: By passing the pointer type, reference passing can be realized and the magnitude value can be directly modified and changed.
Example:
func swap(a, b int) (int, int) { return b, a } func main() { x, y := 3, 5 x, y = swap(x, y) ("After swap: x =", x, ", y =", y) }
5. Variable parameters
Go supports functions that define variable parameters, allowing incoming uncertain number of parameters, using...
to represent variable parameters.
Example:
func sum(nums ...int) int { total := 0 for _, num := range nums { total += num } return total } func main() { ("Sum:", sum(1, 2, 3, 4, 5)) }
6. Anonymous functions and closures
In Go, functions can be used as values, can be assigned to variables, passed as parameters, or defined anonymous functions inside the function. In addition, Go supports closures, that is, external variables can be accessed within functions.
Example:
func main() { add := func(x, y int) int { return x + y } ("10 + 20 =", add(10, 20)) // Closure counter := func() func() int { i := 0 return func() int { i++ return i } }() (counter()) // 1 (counter()) // 2 (counter()) // 3 }
7. Recursion
A recursive function calls itself inside a function. Recursive functions must contain end conditions, otherwise infinite recursion will be caused.
Example:
func factorial(n int) int { if n <= 1 { return 1 } return n * factorial(n-1) } func main() { ("5! =", factorial(5)) }
8. defer statement
defer
Statements are used to delay code execution, and are usually used for resource cleaning operations, such as closing files, unlocking resources, etc.defer
Statements will be executed before the function returns and support multipledefer
, execute in LIFO (latest in first out).
Example:
func main() { ("Start") defer ("Deferred 1") defer ("Deferred 2") ("End") }
The output order is:
Start
End
Deferred 2
Deferred 1
Summarize
- In Go language, functions are the basic units of code multiplexing and logical organization, and support multiple return values, variable parameters, recursion and other features.
- Available
defer
to release resources to ensure that even if the function errors, the resources can be cleaned correctly.
This is the end of this article about the detailed explanation of the usage examples of functions in the go language. For more relevant usage content of go function, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!