简体   繁体   中英

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

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?

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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM