Pass Single Values As Slices With from_ref

Adapt a single &T or &mut T into &[T] or &mut [T] with std::slice::from_ref and from_mut so slice-oriented helpers accept one item with zero copies.

RustData Integrity

Code

snippet
use std::slice;

fn weighted_sum(items: &[i32]) -> i32 {
    items.iter().enumerate().map(|(i, &v)| (i as i32 + 1) * v).sum()
}

fn clamp_all(items: &mut [i32], lo: i32, hi: i32) {
    for v in items.iter_mut() {
        *v = (*v).clamp(lo, hi);
    }
}

fn main() {
    let batch = [10, 20, 30];
    let single = 42;
    println!("batch weighted:  {}", weighted_sum(&batch));
    println!("single weighted: {}", weighted_sum(slice::from_ref(&single)));

    let single_slice = slice::from_ref(&single);
    println!(
        "same stack address: {}",
        std::ptr::eq(single_slice.as_ptr(), &single as *const i32)
    );

    let mut score = 135;
    clamp_all(slice::from_mut(&mut score), 0, 100);
    println!("clamped single: {score}");

    let mut scores = [-5, 50, 120];
    clamp_all(&mut scores, 0, 100);
    println!("clamped batch:  {scores:?}");
}

Execution walkthrough — Pass Single Values As Slices With from_ref

The snippet is organized around the functions weighted_sum, clamp_all and main.

The cycling part of this snippet is for v in items.iter_mut().

Watch out for

  • Zero additional project dependencies or config edits need adding before running.

Using it

Key routine header introduces fn weighted_sum(items: &[i32]) -> i32

Output lines are prefixed (batch weighted:, single weighted:, same stack address:), pairing console messages directly alongside concrete runtime steps.

Start the program and main runs weighted_sum and clamp_all one after another.

Key statements

items.iter().enumerate().map(|(i, &v)| (i as i32 + 1) * v).sum()
}
fn clamp_all(items: &mut [i32], lo: i32, hi: i32) {
    for v in items.iter_mut() {
        *v = (*v).clamp(lo, hi);
    }
}

Interactive Tools for This Topic

FAQ

What does Pass Single Values As Slices With from_ref print when run?
Execute the whole file; each printed line is prefixed with a label like `batch weighted:`, `single weighted:`, `same stack address:`.