6

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?

2
  • In Rust, you might want to read about session types to implement compile-time checked FSMs. Otherwise, an enum with a method consuming self (and an event) and returning Self (or Result<Self>) is more flexible (but transitions are not compile-time checked). Aug 24, 2016 at 18:32
  • 1
    If any of you fine gents/ladies want to answer my new (related) question, it's over here: stackoverflow.com/questions/39130789/…
    – burfl
    Aug 24, 2016 at 18:41

2 Answers 2

5

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.

3

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

4
  • On the other hand... I wonder if there's a trick with Self? Aug 24, 2016 at 18:23
  • I edited the question to add some context. Maybe there's an alternative solution...
    – burfl
    Aug 24, 2016 at 18:30
  • 3
    @burfl: There are alternatives, but as they completely change the question from "how to define a recursive fn" to "how to best implement FSMs"... let's keep to the first question (the second might be off-topic, maybe...) Aug 24, 2016 at 18:34
  • That's fair. I'll undo the edit and perhaps make a new question.
    – burfl
    Aug 24, 2016 at 18:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.