Files
rust/src/doc/trpl/slice-patterns.md
T
Steve Klabnik 665aed059a Backport TRPL, reference, and grammar.
Rather than port each individual change to these files, for the release,
I just waited to do it all at the end, in this commit. Since individual
comits made it to master, everyone should get proper credit in the
main tree, and AUTHORS includes those whose changes are here.
2015-05-13 02:57:13 -04:00

1020 B

% Slice patterns

If you want to match against a slice or array, you can use & with the slice_patterns feature:

#![feature(slice_patterns)]

fn main() {
    let v = vec!["match_this", "1"];

    match &v[..] {
        ["match_this", second] => println!("The second element is {}", second),
        _ => {},
    }
}

The advanced_slice_patterns gate lets you use .. to indicate any number of elements inside a pattern matching a slice. This wildcard can only be used once for a given array. If there's an identifier before the .., the result of the slice will be bound to that name. For example:

#![feature(advanced_slice_patterns, slice_patterns)]

fn is_symmetric(list: &[u32]) -> bool {
    match list {
        [] | [_] => true,
        [x, inside.., y] if x == y => is_symmetric(inside),
        _ => false
    }
}

fn main() {
    let sym = &[0, 1, 4, 2, 4, 1, 0];
    assert!(is_symmetric(sym));

    let not_sym = &[0, 1, 7, 2, 4, 1, 0];
    assert!(!is_symmetric(not_sym));
}