Go语言中,一个被调用的函数如何获取调用函数的参数访问权限?

huangapple go评论84阅读模式
英文:

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 (
	&quot;fmt&quot;
	&quot;sort&quot;
)

func main() {
	order := &quot;abcd&quot;
	s := &quot;bca&quot;
	fmt.Printf(&quot;ans: %v\n&quot;, customSortString(order, s))
}

func customSortString(order string, s string) string {
	sort.Slice([]byte(s), func(a, b int) bool {
		fmt.Printf(&quot;order: %v\n&quot;, order) // &lt;------ How does this work? order is not passed to sort.Slice() function. 
		return s[a] &lt; s[b]
	})
	return &quot;&quot;
}

答案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.

huangapple
  • 本文由 发表于 2023年3月29日 06:29:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/75871593.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定