我正在学习Rust,仍在努力理解它。考虑下面的Go定义:
type FnType func(paramType) FnType
这只是一个返回相同类型函数的函数。在Rust中能否实现类似的功能呢?理想情况下,是否可以通用地实现,以便客户端指定paramType
?
我在文档中进行了一些探索,并在游乐场上进行了尝试,我认为我已经能够自己回答这个问题了,尽管它确实需要一个中间类型:特定的枚举
。
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
}
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.
self
(和事件)并返回Self
(或Result<Self>
)的方法的enum
更加灵活(但转换不是编译时检查的)。 - Matthieu M.