Skip to content

Unsound: Borrowck missing that closure needs to be "move"  #35139

Closed
@diwic

Description

@diwic

Here's as far as I've come in minifying the problem. It gives bad result on both Stable, Beta and Nightly according to playground.

pub trait MethodType: Sized + Default {
    type GetProp: ?Sized;
}

#[derive(Default, Debug, Copy, Clone)]
pub struct MTFn;

impl<'a> MethodType for MTFn {
    type GetProp = Fn(&mut String) -> Result<(), ()> + 'a;
}

pub struct Property<M: MethodType> {
    get_cb: Option<Box<M::GetProp>>,
}

impl<'a> Property<MTFn> {
    pub fn on_get<H>(mut self, handler: H) -> Property<MTFn>
        where H: Fn(&mut String) -> Result<(), ()> + 'a {
        self.get_cb = Some(Box::new(handler) as Box<_>);
        self
    }
}

fn main() {
    let z: Option<Property<MTFn>>;
    {
        let mut v = format!("ABC DEF GHI JKL");
        let p = Property { get_cb: None };

        // This line should give an error indicating we need a "move" closure
        z = Some(p.on_get(|s| { *s = v.clone(); Ok(()) }));

        // Destroy v to show the error
        v = format!("MNO PQR");
    }
    let mut q = format!("STU");
    let _ = (z.unwrap().get_cb.unwrap())(&mut q);
    println!("{}", q); // Prints "STU PQR" !
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions