我试图在Go中的另一个函数中定义一个递归函数,但我正在努力获得正确的语法.我正在寻找这样的东西:
func Function1(n) int {
a := 10
Function2 := func(m int) int {
if m <= a {
return a
}
return Function2(m-1)
}
return Function2(n)
}
Run Code Online (Sandbox Code Playgroud)
我想将Function2保留在Function1的范围内,因为它正在访问其范围的某些元素.
我怎么能在Go中这样做?
非常感谢
这个问题:如何测试Go中的os.exit场景(以及其中最高的投票答案),阐述了如何os.Exit()在go中测试场景.由于os.Exit()不能轻易拦截,使用的方法是重新调用二进制文件并检查退出值.这个方法在Andrew Gerrand(Go团队的核心成员之一)的演示文稿第23页中描述; 代码非常简单,下面将全文转载.
相关的测试和主文件看起来像这样(请注意,这对文件本身就是一个MVCE):
package foo
import (
"os"
"os/exec"
"testing"
)
func TestCrasher(t *testing.T) {
if os.Getenv("BE_CRASHER") == "1" {
Crasher() // This causes os.Exit(1) to be called
return
}
cmd := exec.Command(os.Args[0], "-test.run=TestCrasher")
cmd.Env = append(os.Environ(), "BE_CRASHER=1")
err := cmd.Run()
if e, ok := err.(*exec.ExitError); ok && !e.Success() {
fmt.Printf("Error is %v\n", e)
return
}
t.Fatalf("process ran with err %v, want exit status 1", err)
}
Run Code Online (Sandbox Code Playgroud)
和
package …Run Code Online (Sandbox Code Playgroud) Go支持嵌套struct里面的函数,但没有嵌套函数,除了lambda,是否意味着没有办法在函数内定义嵌套类?
func f() {
// nested struct Cls inside f
type Cls struct {
...
}
// try bounding foo to Cls but fail
func (c *Cls) foo() {
...
}
}
Run Code Online (Sandbox Code Playgroud)
因此,类内部功能削弱感觉有点奇怪.
任何提示?
go ×3
architecture ×1
coveralls ×1
function ×1
nested ×1
recursion ×1
testing ×1
unit-testing ×1