我是 Go 编程的新手,那么如何在这段代码中实现递归而不是 for 循环?
package main
import (
"fmt"
)
func main() {
var n int
fmt.Scan(&n)
set(n)
}
func set(n int) {
a := make([]int, n)
for i := 0; i < n; i++ {
fmt.Scan(&a[i])
}
fmt.Println(a)
}
我不确定你想要递归什么。但据我了解,您的问题是将 for 循环更改为递归,因此我以函数式编程风格将其变成了闭包中的尾递归。
func set(n int) {
a := make([]int, n)
var setRecursive func(int) // declare a function variable, which take an int as param.
setRecursive = func(i int) { // set the function in closure, so a and n is available to it.
if i == 0 { // end point of the recursion, return.
return
}
Scan(&a[n-i]) // Use fmt.Scan out of playground
setRecursive(i - 1) // tail recursion.
}
setRecursive(n) // call the function, start the recursion.
fmt.Println(a)
}
如果你想让事情更简单,你可以去掉闭包部分,把Scan(&a[n-i])
这一行移到setRecursive(n)
后面,就像下面:
func SetRecursive(a []int, n int) {
if n==0 {
return
}
SetRecursive(a,n-1) // recurse first, so we can scan in the right order.
Scan(&a[n-1])
}
Playground :https://play.golang.org/p/0io190tyviE