Home >Backend Development >Golang >How does a called function in Go access the parameters of the calling function?
The function called in Go can obtain the parameters of the calling function through the function parameters. In Go, parameters can be passed to functions by value or reference, and the function can obtain the value or pointer passed by the caller through the parameters. If the parameter is a value type, operations inside the function will be performed on the copy of the parameter and will not affect the original value passed by the caller. If the parameter is a pointer type, the operation inside the function will modify the original value pointed to by the pointer. In this way, functions can access and modify the parameters of the calling function, allowing for more flexible functionality. Whether it is a value type or pointer type parameter, the function can obtain the value or pointer passed by the caller through the parameter, and perform related operations inside the function.
Please refer to the reference code https://go.dev/play/p/yig2b6dkcoc (also pasted here):
Just like this code - the argument order is not passed to the sort.slice() function, but it is printed nicely in the call to the less() method of the sort package.
What are the attributes that implement this function?
package main import ( "fmt" "sort" ) func main() { order := "abcd" s := "bca" fmt.Printf("ans: %v\n", customSortString(order, s)) } func customSortString(order string, s string) string { sort.Slice([]byte(s), func(a, b int) bool { fmt.Printf("order: %v\n", order) // <------ How does this work? order is not passed to sort.Slice() function. return s[a] < s[b] }) return "" }
https://www.php.cn/link/58b7483ba899e0ce4d97ac5eecf6fa99:
Function literals are closures : they can reference variables defined in surrounding functions. These variables are then shared between surrounding functions and function literals, and they persist as long as they are accessible.
The above is the detailed content of How does a called function in Go access the parameters of the calling function?. For more information, please follow other related articles on the PHP Chinese website!