borrowing

Rust Borrow arrays and vectors as slices

Use a shared slice parameter to inspect a contiguous sequence of elements without requiring a particular owning container or fixed array length. Arrays and vectors can provide these views through borrowing and coercion. Expected output (not executed): 12 12 Why: Both inputs become shared slice views and remain owned by their callers. Common mistake: Accepting Vec<i32> by value when an operation only needs a read-only sequence.

Formal Syntax & Structure

rust syntaxrust
fn inspect(items: &[T]) { ... }

Working Example

Example Snippetrust
fn total(items: &[i32]) -> i32 {    items.iter().sum()}fn main() {    let fixed = [2, 4, 6];    let dynamic = vec![5, 7];    println!("{} {}", total(&fixed), total(&dynamic));}
Rust Reference