How to return a closure which returns an impl trait in Rust

314 Views Asked by At

I am using druid ui kit and this is working

fn build_list_item() -> impl Widget<TodoItem> {
    Flex::row()
        .with_child(Checkbox::new("").lens(TodoItem::completed))
        .with_flex_child(
            Label::new(|item: &TodoItem, _: &_| item.description.clone()),
            1.0,
        )
}
// and then
List::new(|| build_list_item())

But I want to achieve this

List::new(build_list_item())

So I modified the function like this

fn build_list_item() -> impl Fn() -> impl Widget<TodoItem> {
    || {
        Flex::row()
            .with_child(Checkbox::new("").lens(TodoItem::completed))
            .with_flex_child(
                Label::new(|item: &TodoItem, _: &_| item.description.clone()),
                1.0,
            )
    }
}

and got compiler error like

error[E0562]: `impl Trait` not allowed outside of function and method return types
  --> src/main.rs:33:39
   |
33 | fn build_list_item2() -> impl Fn() -> impl Widget<TodoItem> {
   |                                       ^^^^^^^^^^^^^^^^^^^^^

How to fix it?

1

There are 1 best solutions below

0
On

Because the size of the returned Widget is not known at compile time You could use the following solution:

fn build_list_item() -> impl Fn() -> Flex<TodoItem> {
    &|| {Flex::row()
        .with_child(Checkbox::new("").lens(TodoItem::completed))
        .with_flex_child(
            Label::new(|item: &TodoItem, _: &_| item.description.clone()),
            1.0,
        )}
}
// and then
List::new(build_list_item());