Borrow Slices Instead Of Vec Parameters

Write read-only helpers against &[T] and mutating helpers against &mut [T]; Vecs and arrays deref-coerce into the borrowed slice the function actually needs.

RustData Integrity

Code

rustsnippet
28 lines
// 参数(parameters)用切片(slice)借用(borrow)而不是 &Vec:
// clippy 的 ptr_arg lint 也会提醒 &Vec 参数
fn average(values: &[i64]) -> f64 {
    if values.is_empty() {
        return 0.0;
    }
    values.iter().sum::<i64>() as f64 / values.len() as f64
}

// 需要修改元素时用 &mut [i64],同样接受 Vec 与数组
fn clamp_all(values: &mut [i64], low: i64, high: i64) {
    for v in values.iter_mut() {
        *v = (*v).clamp(low, high);
    }
}

fn main() {
    let vec = vec![10, 90, 30];
    let array = [10, 90, 30];

    // &Vec<i64> 与 &[i64; 3] 都自动解引用(deref coercion)成 &[i64]
    println!("vec avg: {:.2}", average(&vec));
    println!("array avg: {:.2}", average(&array));

    let mut readings = vec![5, 120, 42];
    clamp_all(&mut readings, 0, 100);
    println!("clamped: {readings:?}");
}

How the snippet works

Borrow Slices Instead Of Vec Parameters keeps everything in the functions average, clamp_all and main.

The file repeats itself only inside for v in values.iter_mut().

Applying it

The primary signature is fn average(values: &[i64]) -> f64

Running the file prints labeled results such as vec avg:, array avg:, clamped: — each operation’s effect is visible in the output.

The entry point wires average and clamp_all together — run it once and the whole demo flows.

Statements that matter

fn clamp_all(values: &mut [i64], low: i64, high: i64) {
for v in values.iter_mut() {
*v = (*v).clamp(low, high);
}
}
fn average(values: &[i64]) -> f64 {
if values.is_empty() {
return 0.0;
}
values.iter().sum::<i64>() as f64 / values.len() as f64
}

Interactive Tools for This Topic

FAQ

What does Borrow Slices Instead Of Vec Parameters print when run?
Running the file directly is enough — expect labeled output lines such as `vec avg:`, `array avg:`, `clamped:`.