Return the closures

fn demo<T>(y: i32) -> impl Fn(i32) -> T {
    let closure = move |x: i32| { x + y };
    closure
}
fn main() {
    let test = demo(1);
}

Why can't I return this closure type? Doesn't T stand for any type? How can I modify the code to achieve the same purpose

This means that the type is chosen by the caller. So, for example, if I call demo::<String>, then you would need to return a Fn(i32) -> String, which you aren't doing.

It's a bit difficult to tell you how to fix it without knowing your goal in more details.

2 Likes

It will be better if you could provide a detailed description.
As for return this closure type, my example is listed below.

use std::ops::Add;
fn demo<T: Add<Output=T>>(y: T) -> impl FnOnce(T) -> T {
    let closure = move |x: T| -> T { x.add(y) };
    closure
}
fn main() {
    let test = demo::<i32>(1);
    println!("test(2) = {}", test(2));
}
2 Likes

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.