Lint request: require explicit lifetimes for impls with references
Author: nazar-pcCreated Sep 26, 2026Updated Sep 30, 2026
LabelsA-lint
Seemingly straightforward code has unexpected lifetimes elided leading to unsound implementation:
#[repr(transparent)]
pub struct Wrapper(pub [u8; 4]);
// Elided lifetimes in the impl header are independent:
// `impl<'a, 'b> From<&'a Wrapper> for &'b [u8; 4]`
impl From<&Wrapper> for &[u8; 4] {
fn from(value: &Wrapper) -> Self {
// `&*core::ptr::from_ref(value).cast::<[u8; 4]>()` behaves the same
unsafe { core::mem::transmute(value) }
}
}
fn dangling() -> &'static [u8; 4] {
let wrapper = Wrapper([1, 2, 3, 4]);
<&[u8; 4]>::from(&wrapper)
}
fn main() {
println!("{:?}", dangling());
}Using safe APIs (possible in this case, but not in general) shows why:
error: lifetime may not live long enough
--> src/main.rs:8:9
|
7 | fn from(value: &Wrapper) -> Self {
| - ---- return type is &'2 [u8; 4]
| |
| let's call the lifetime of this reference `'1`
8 | &value.0
| ^^^^^^^^ associated function was supposed to return data with lifetime `'2` but it is returning data with lifetime `'1`Impl should be written like this to be explicit about it since this is most likely what user intends anyway:
impl<'a From<&'a Wrapper> for &'a [u8; 4] {
fn from(value: &'a Wrapper) -> Self {
unsafe { core::mem::transmute(value) }
}
}I found this to be a particularly sneaky pitfall, hence lint request.
Source: rust-lang/rust-clippy