为什么在Go语言中的foo()函数内部有一个独立的test()函数?

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

Why do we have an isolated test() inside foo() in Go?

问题

为什么下面代码中的test()函数被组织成这样,而不是将test()中的所有内容取出并放入foo()中呢?谢谢!

func foo() error{
    ...
    err = test() error {
        ...
        ...
    }
    ...
}

这种组织方式可能是为了将test()函数的逻辑与foo()函数的逻辑分开,以提高代码的可读性和可维护性。将test()函数嵌套在foo()函数中可以使代码更加清晰,每个函数都有自己的职责和功能。这样做还可以避免在foo()函数中重复编写test()函数的逻辑,提高代码的复用性。

英文:

Why is test() function in the following code organized like this, instead of getting everything in the test() out and putting them into foo()? Thanks!

func foo() error{
    ...
    err = test() error {
        ...
        ...
    }
    ...
}

答案1

得分: 1

有几个原因你可能想要像这样的内部函数,但迄今为止最常见的用途是当你需要在内部函数中使用包含函数的局部变量时。为什么需要内部函数呢?有时你需要将它传递给一个库,或者你需要在godefer语句中使用它。

内部函数会“捕获”来自外部函数的任何变量,并且即使外部函数返回后,这些变量仍然有效。因此,以这种方式定义的函数被称为“闭包”。

常见的用途是用于特定库的回调函数等。有时,即兴创建所需的函数会更加方便。

另一个常见的用途是在代码块中使用deferdefer只能用于函数,并且通常需要外部函数的变量。通常,你会在使用recover和命名返回值时看到这种情况。显然,这与原因#1重叠。

最后,有时你想要并行运行函数的某些部分,因此你创建一个闭包,并将其作为goroutine与go一起调用。

当然,闭包还有其他用途...

英文:

There are several reasons why you may want a inner function like this, but by far the most common use is when you need to use a local variable from the containing function in the inner function. Why an inner function at all? Sometimes you need it to pass into an library, or you need it for go or defer statements.

The inner function "closes over" any variables it uses that come from the outer function, and these variables remain valid even after the outer function returns. For this reason functions defined this way are called "closures".

A common use is callbacks and such for use with certain libraries. Sometimes its just easier to make the function you need on the spot.

Another common use is if you want to use defer with a block of code. defer only works with functions, and often you need variables from the outer function. Generally you see this case used with recover and named return values. Obviously this overlaps with reason #1.

Finally sometimes you want to run parts of a function in parallel, so you create a closure and call it in as a goroutine with go.

There are of course other uses for closures...

huangapple
  • 本文由 发表于 2017年7月27日 11:48:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/45341058.html
匿名

发表评论

匿名网友

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

确定