Implicit `&Vec<T>` to `&[T]` conversion, but how?

Can someone explain, why a Vec<T> to &[T] works without boilerplate code?

fn main() {
    let v = vec![10, 20, 30];
    let f = first(&v); // why does this conversion from `Vec` to `&[]` work?
    
    println!("first of {v:?} is {f:?}");
}

fn first(slice: &[u32]) -> Option<u32> {
    slice.get(0).copied()
}

That's a Deref coercion, Treating Smart Pointers Like Regular References with the Deref Trait - The Rust Programming Language.

1 Like

oh thank you, didn't know that.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.