gpt4 book ai didi

go - 仅在 Golang 中递归的最外层函数上运行语句

转载 作者:IT王子 更新时间:2023-10-29 02:28:58 28 4
gpt4 key购买 nike

我有一个递归函数,我希望只在最外层调用该函数时执行一些语句。如何实现此功能?

func fact(n int) int {
if n == 0 {
return 1
}
fact := n * fact(n-1)
if outer_most{
fmt.Printf(strconv.Itoa(n))
}
return fact
}
func main() {
fact(4)
}

这应该只打印 4

最佳答案

要回答这个问题本身:如果出于某种原因您真的想运行仅用于最外层 func 调用并且不想更改 api 的东西,Golang 有一个运行时库。你可以这样做:

package main

import (
"fmt"
"runtime"
"strconv"
)

func outer_most() bool {
pc:=make([]uintptr,2)
runtime.Callers(2,pc) //skip: 1 - runtime.Caller, 2 - outer_most itself
return runtime.FuncForPC(pc[0])!=runtime.FuncForPC(pc[1]) // test if the caller of the caller is the same func, otherwise it is the outermost
}

func fact(n int) int {
if n == 0 {
return 1
}
fact := n * fact(n-1)
if outer_most() {
fmt.Printf(strconv.Itoa(n))
}
return fact
}

func main() {
fact(4)
}

Playground :https://play.golang.org/p/ro1ZOn6yIR7这不是什么好的做法,但最直接地解决问题。

注意:使用全局变量很可能会导致毛刺。每次调用func的时候都需要设置,如果并发,就会出现data race。

如果您对每次递归调用(可能是无数次)分配额外的 bool 参数这一事实感到不安,您可以查看@Adrian 的回答或将其包装为 bool 的方法。

关于go - 仅在 Golang 中递归的最外层函数上运行语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47990587/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com