Indirectly referring to the return type of a function

Hi, suppose I have the following code:

fn foo() -> impl Iterator<Item=i32> {
    let closure = 42;
    vec![1, 2, 3].into_iter().map(move |v| v + closure)
}
type FooReturnType = ...

I would like to use the return type of foo elsewhere but can't type it out manually because of the Map / closure. Ideally I would like to be able to reference the exact type foo returns through a nice name like FooReturnType, is there a way to do this?

This is RFC 2515, which is implemented but currently unstable: https://github.com/rust-lang/rust/issues/63063

1 Like

What you can do now is to use dyn Trait.

fn foo() -> Box<dyn Iterator<Item=i32>> {
    let closure = 42;
    Box::new(vec![1, 2, 3].into_iter().map(move |v| v + closure))
}

Aw sorry, I forgot to clarify that I do not want to use trait objects

Thanks!

Another option is to implement the trait yourself.

struct MyIterator {
    inner: std::vec::IntoIter<i32>,
    closure: i32,
}
impl Iterator for MyIterator {
    type Item = i32;
    fn next(&mut self) -> Option<i32> {
        self.inner
            .next()
            .map(|v| v + self.closure)
    }
}

fn foo() -> MyIterator {
    MyIterator {
        inner: vec![1, 2, 3].into_iter(),
        closure: 42,
    }
}

But besides this, you would have to use unstable Rust.

2 Likes

You could do something like this if you're using a function, not a capturing closure:

fn foo() -> std::iter::Map<std::vec::IntoIter<i32>, fn(i32) -> i32> {
    vec![1, 2, 3].into_iter.map((|x| x + 42) as fn(i32) -> i32)
}
1 Like

more precisely "using a function pointer"

which is technically not a trait object but similar to trait objects in how it is adding overhead in the form of dynamic function calls

just wanted to make sure, this fact isn't overlooked here by people less familiar with Rust functions vs function pointers

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.