`AsRef` and lifetimes
⚓ Rust 📅 2025-07-15 👤 surdeus 👁️ 17I tried something like this today, and it failed to compile:
fn ret_ref<'a>(x:&'a mut Vec<u8>)->&'a[u8]{
x.as_ref()
}
error[E0515]: cannot return value referencing function parameter `x`
--> src/lib.rs:2:5
|
2 | x.as_ref()
| -^^^^^^^^^
| |
| returns a value referencing data owned by the current function
| `x` is borrowed here
This however works fine:
fn ret_ref<'a>(x:&'a mut Vec<u8>)->&'a[u8]{
(&*x).as_ref()
}
I am guessing that one refers to <&Vec<u8> as AsRef> and the other to <&mut Vec<u8> as AsRef>.
Indeed, this also fails:
fn ret_ref<'a>(x:&'a mut Vec<u8>)->&'a[u8]{
(&mut *x).as_ref()
}
Why are they different?
5 posts - 4 participants
🏷️ rust_feed