# Function rustc_hir_typeck::upvar::truncate_capture_for_optimization

source ·

    fn truncate_capture_for_optimization(
        place: Place<'_>,
        curr_mode: UpvarCapture
    ) -> (Place<'_>, UpvarCapture)

Expand description

Reduces the precision of the captured place when the precision doesn’t yield any benefit from borrow checking perspective, allowing us to save us on the size of the capture.

Fields that are read through a shared reference will always be read via a shared ref or a copy, and therefore capturing precise paths yields no benefit. This optimization truncates the rightmost deref of the capture if the deref is applied to a shared ref.

Reason we only drop the last deref is because of the following edge case:

    struct MyStruct<'a> {
       a: &'static A,
       b: B,
       c: C<'a>,
    }

    fn foo<'a, 'b>(m: &'a MyStruct<'b>) -> impl FnMut() + 'static {
        || drop(&*m.a.field_of_a)
        // Here we really do want to capture `*m.a` because that outlives `'static`

        // If we capture `m`, then the closure no longer outlives `'static`
        // it is constrained to `'a`
    }