Recursion And Tail Calls In Go这篇文章讲了用goroutine
实现函数递归调用:这样做可以避免过多函数调用引起的堆栈空间的不断增大,感觉很巧妙。以下是例子代码:
package main
import "fmt"
func recursiveCall(product int, num int, ch chan int) {
product += num
if num == 1 {
ch <- product
return
}
go recursiveCall(product, num - 1, ch)
}
func main() {
ch := make(chan int)
go recursiveCall(0, 4, ch)
product := <-ch
fmt.Printf("Product is %d\n", product)
}
执行结果如下:
Product is 10