How can I define a Rust function type which returns its own type?

我的梦境 提交于 2020-01-03 14:17:37

问题


I'm learning Rust, and still very much trying to get my head around it. Consider the following Go definition:

type FnType func(paramType) FnType

It's just a function that returns a function of the same type. Can something similar be implemented in Rust? And, ideally, can it be done generically, so that paramType is specified by the client?


回答1:


I did some digging in the docs and took to the playground and I think I've been able to answer this myself, although it does require an intermediary type: an enum, to be specific.

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
}

You can verify that it runs on the playground.




回答2:


Cyclic types are unsupported in Rust:

type a = fn(String) -> a;

Yields the following error:

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.

See on playground



来源:https://stackoverflow.com/questions/39130293/how-can-i-define-a-rust-function-type-which-returns-its-own-type

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!