Fixing borrowed data escapes outside of closure

Your closure needs to take a &Node with one particular lifetime (matching that in the type of v), but when the compiler sees the &Node annotation, it thinks you want it to make a closure that takes any lifetime.

Workaround one: put the annotation in the closure body instead.

    let mut closure2 = |node| {
        let node: &Node = node;
        use_node(&node.line);

        v.push(node);
    };

Workaround two: funnel the closure through an identity function with the bounds you want.

    // N.b. a closure that takes a `&Node` with one specific lifetime,
    // not a closure that takes a `&Node` with any lifetime
    fn funnel<'a, F: FnMut(&'a Node)>(f: F) -> F { f } 

    let mut closure2 = funnel(|node| {
        use_node(&node.line);
        v.push(node);
    });
2 Likes