Why does this snippet fail to compile?

⚓ Rust    📅 2026-05-14    👤 surdeus    👁️ 2      

surdeus

fn foo(dst: &mut i32, a: i32) {
    *dst = a;
}

fn bar() {
    let f = foo as fn(_, _);
    loop {
        let mut dst = 0;
        f(&mut dst, 1);
    }
}

rustc fails with the following error message

error[E0597]: `dst` does not live long enough
  --> <source>:9:11
   |
 8 |         let mut dst = 0;
   |             ------- binding `dst` declared here
 9 |         f(&mut dst, 1);
   |         - ^^^^^^^^ borrowed value does not live long enough
   |         |
   |         borrow later used here
10 |     }
   |     - `dst` dropped here while still borrowed

But I can't make any sense of the message -- the dst parameter of f should be instantiated with a smaller lifetime than the lifetime of the dst variable. It says dst is dropped while still borrowed, but I can't figure out where the borrow is. Afaiu f cannot keep the borrow because it is instantiated with a smaller lifetime.

Also, this only occurs with the fn cast and some sort of loop (loop, for, while all work)

7 posts - 4 participants

Read full topic

🏷️ Rust_feed