rchunks Batches From The Tail

Walk slices backwards in fixed batches with rchunks and rchunks_exact, so alignment anchors to the last element instead of the first.

RustData Integrity

Code

rustsnippet
25 lines
fn main() {
    let digits = [1, 2, 3, 4, 5, 6, 7];

    // rchunks:从尾部对齐分组,头部可能不满一批
    let groups: Vec<&[i32]> = digits.rchunks(3).collect();
    println!("rchunks: {groups:?}");

    // rchunks_exact:跳过头部不满批的余数
    let exact: Vec<&[i32]> = digits.rchunks_exact(3).collect();
    println!("rchunks_exact: {exact:?}");

    // 余数通过 take_remainder 单独取回
    let head = digits.rchunks_exact(3).take_remainder();
    println!("head remainder: {head:?}");

    // 典型场景:千分位分组从右对齐
    let mut grouped = String::new();
    for (i, group) in [7, 4, 5, 6, 1, 2, 3].iter().rchunks(3).enumerate() {
        if i > 0 {
            grouped.insert(0, ',');
        }
        grouped.insert_str(0, &group.iter().map(|d| d.to_string()).collect::<String>());
    }
    println!("grouped: {grouped}");
}

How the snippet works

rchunks Batches From The Tail reduces to the function main.

A single loop drives the file — for (i, group) in [7, 4, 5, 6, 1, 2, 3].iter().rchunks(3).enumerate().

What to watch for

  • No setup phase: the platform supplies every API the file touches.

Using it

Entry signature: fn main()

The file’s steps are announced right in the output: rchunks:, rchunks_exact:, head remainder:.

Key statements

grouped.insert_str(0, &group.iter().map(|d| d.to_string()).collect::<String>());
let exact: Vec<&[i32]> = digits.rchunks_exact(3).collect();
let groups: Vec<&[i32]> = digits.rchunks(3).collect();

Interactive Tools for This Topic

FAQ

What does rchunks Batches From The Tail print when run?
The script runs standalone; its 4 labeled outputs include `rchunks:`, `rchunks_exact:`, `head remainder:`.