英文:
How does a function called in Go, get the access to calling functions parameters?
问题
请参考以下代码 https://go.dev/play/p/yIG2B6DKcoc(也在此处粘贴):
在这段代码中,参数order没有传递给sort.Slice()函数,但在sort包的调用Less()方法中,它仍然被正确打印出来。
是什么属性使得这种情况成为可能?
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) // <------ 这是如何工作的?order没有传递给sort.Slice()函数。
return s[a] < s[b]
})
return ""
}
英文:
See code for reference https://go.dev/play/p/yIG2B6DKcoc (also pasted here):
As in this piece of code - the parameter order is not passed to sort.Slice() function, yet it gets printed fine in the called Less() method of sort package.
What is the property that enables this?
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 ""
}
答案1
得分: 3
https://go.dev/ref/spec#Function_literals:
函数字面量是闭包:它们可以引用在周围函数中定义的变量。这些变量在周围函数和函数字面量之间共享,并且只要它们可访问,它们就会一直存在。
英文:
https://go.dev/ref/spec#Function_literals:
> Function literals are closures: they may refer to variables defined in a surrounding function. Those variables are then shared between the surrounding function and the function literal, and they survive as long as they are accessible.
答案2
得分: 1
Go支持匿名函数,它们可以形成闭包。
在Go中,闭包是一个匿名内部函数,它可以访问在其创建时所在作用域中的变量。即使外部函数执行结束并且作用域被销毁,闭包仍然可以访问这些变量。
英文:
> Go supports anonymous functions, which can form closures.
In Go, a closure is an anonymous inner function that has access to the variables from the scope in which it was created. This applies even when the outer function finishes execution and the scope gets destroyed.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论