我正在尝试实现一个返回递归闭包的函数,但是我不确定如何在函数签名中表达这一点。以下是Python中可工作实现的示例代码:
def counter(state):
def handler(msg):
if msg == 'inc':
print state
return counter(state + 1)
if msg == 'dec':
print state
return counter(state - 1)
return handler
c = counter(1)
for x in range(1000000):
c = c('inc')
以及Rust的伪代码。
enum Msg {
Inc,
Dec
}
fn counter(state: Int) -> ? {
move |msg| match msg {
Msg::Inc => counter(state + 1),
Msg::Dec => counter(state - 1),
}
}