Slice Patterns For Array Destructuring

Destructure slices in match arms: fixed-length patterns assert exact element counts, and head with rest @ .. binds the remaining items as a subslice.

RustData Integrity

Code

rustsnippet
22 lines
fn describe(readings: &[i32]) -> String {
    match readings {
        [] => "empty".to_string(),
        // 固定长度模式:只匹配恰好一个 / 两个元素的切片
        [only] => format!("single: {only}"),
        [first, second] => format!("pair: {first} vs {second}"),
        // head/tail 拆分:rest @ .. 把剩余元素绑定为子切片
        [head, rest @ ..] => format!("head {head}, {} more: {rest:?}", rest.len()),
    }
}

fn main() {
    let data = [7, 11, 13, 17];
    println!("{}", describe(&data));
    println!("{}", describe(&data[..2]));
    println!("{}", describe(&data[..1]));
    println!("{}", describe(&[]));

    // let 解构固定长度数组:.. 吞掉剩余元素
    let [a, b, ..] = data;
    println!("first two: {a} {b}");
}

Inside the snippet

Slice Patterns For Array Destructuring comes down to the functions describe and main.

Branching goes through match, whose exhaustiveness checking turns forgotten cases into compile errors.

Using it

Entry signature: fn describe(readings: &[i32]) -> String

Running the file prints labeled results such as first two: — each operation’s effect is visible in the output.

The sequence describe lives in main; running the file triggers it.

Key statements

match readings {
[] => "empty".to_string(),
// 固定长度模式:只匹配恰好一个 / 两个元素的切片
[only] => format!("single: {only}"),
[first, second] => format!("pair: {first} vs {second}"),
// head/tail 拆分:rest @ .. 把剩余元素绑定为子切片
[head, rest @ ..] => format!("head {head}, {} more: {rest:?}", rest.len()),
}

Interactive Tools for This Topic

FAQ

What does Slice Patterns For Array Destructuring print when run?
Execute the whole file; each printed line is prefixed with a label like `first two:`.