Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

generics

rust

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?

like image 544
burfl Avatar asked Aug 24 '16 18:08

burfl


1 Answers

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.

like image 69
burfl Avatar answered Sep 28 '22 00:09

burfl