Go function
The Go function is a reference type that can be assigned to variables. Apart from the built-in functions provided by the Go standard library, developers can define their own functions.
Function Definition
//If a function has no parameters, the parameter list can be omitted
//If a function has no return values, the return type list can be omitted
func functionName(parameterList) (returnTypeList) {
//Function body
}
func getUserInfo(uid int) (string, string) {
userInfo := services.User{}.getUserInfo(uid)
return userInfo.Username, userInfo.Sex
}
Function Parameters
Functions can pass parameters in the following ways:
- Value Passing: When a function is called, the actual parameters are copied (value copy) and passed to the function. Any modifications made to the parameters within the function do not affect the actual parameters.
- Reference Passing: When a function is called, the address of the actual parameters (address copy) is passed to the function. Any modifications made to the parameters within the function will affect the actual parameters.
//Value Passing
func swap1(x, y int) (int, int) {
var temp int
temp = x
x = y
y = temp
return x, y
}
//Reference Passing
func swap2(x, y *int) {
var temp int
temp = *x
*x = *y
*y = temp
}
func main() {
var a, b = 1, 2
var c, d = 3, 4
fmt.Println("before:", a, b)
a, b = swap1(a, b)
fmt.Println("after:", a, b)
fmt.Println("before:", c, d)
swap2(&c, &d)
fmt.Println("after:", c, d)
}
By default, Go uses value passing. If the object being passed by value is too large, for performance considerations, reference passing can be adopted (even if there's no need to affect the actual parameters).
Callbacks
In Go, functions can also be passed as parameters, allowing them to be used as callbacks. Callbacks are a very common approach, typically used in scenarios such as handling asynchronous operations, event handling, or user-defined behaviors.
func preprocess(data map[string]any, callback func(int64)) {
//Do something...
//After completion, call the callback function
callback(1)
}
func workerCallback(previousStep int64) {
fmt.Println("My step is:", previousStep + 1)
}
func main() {
preprocess(map[string]any{}, workerCallback)
}
Variadic Parameters
Variadic parameters (or unspecified parameters) refer to parameters with an uncertain number but of the same type. Variadic parameters are essentially a slice, there can be at most one, and it must be placed at the end.
func search(schoolId int, args ...any) (Result, error) {
//...
}
Similar to other languages, Go also supports anonymous functions, closures, recursion, and so on.
Take a break
πππ γJade Dynasty EP45γGui Li, Jin Ping'er and Xiao Bai. Maybe, this is love.