如何定义一个返回其自身类型的Rust函数类型?

6

我正在学习Rust,仍在努力理解它。考虑下面的Go定义:

type FnType func(paramType) FnType

这只是一个返回相同类型函数的函数。在Rust中能否实现类似的功能呢?理想情况下,是否可以通用地实现,以便客户端指定paramType


在Rust中,您可能想要了解会话类型以实现编译时检查的有限状态机。否则,使用一个消耗self(和事件)并返回Self(或Result<Self>)的方法的enum更加灵活(但转换不是编译时检查的)。 - Matthieu M.
1
如果有任何绅士或女士想要回答我的新问题(相关),请到这里:http://stackoverflow.com/questions/39130789/in-rust-what-is-the-most-idiomatic-way-to-implement-a-simple-fsm - burfl
2个回答

5

我在文档中进行了一些探索,并在游乐场上进行了尝试,我认为我已经能够自己回答这个问题了,尽管它确实需要一个中间类型:特定的枚举

fn main() {
    let mut state = State::Some(first);
    while let State::Some(s) = state {
        state = s(0)
    }
}

enum State<T> {
    Some(fn(T) -> State<T>),
    None,
}

fn first(_: i32) -> State<i32> {
    println!("First");
    State::Some(second)
}

fn second(_: i32) -> State<i32> {
    println!("Second");
    State::None
}

你可以在playground上验证它是否可运行。

3
循环类型在Rust中不被支持:
type a = fn(String) -> a;

产生以下错误:
error: unsupported cyclic reference between types/traits detected [--explain E0391]
 --> <anon>:1:24
  |>
1 |> type a = fn(String) -> a;
  |>                        ^
note: the cycle begins when processing `a`...
note: ...which then again requires processing `a`, completing the cycle.

请在playground上查看。


另一方面...我想知道Self是否有什么诀窍? - Matthieu M.
我编辑了问题并添加了一些上下文。也许有另一种解决方案... - burfl
3
有替代方案,但它们会完全改变问题,从“如何定义递归函数”变为“如何最好地实现FSM”……让我们坚持第一个问题(也许第二个问题不是主题……) - Matthieu M.
这很公平。我会撤销编辑,也许提出一个新问题。 - burfl

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接