In today's Rust, you can use pattern-matching to check that a slice has a specific length:
match slice {
&[_, _, _] => println!("slice has length 3"),
_ => (),
}
Or check that it has a minimum length:
match slice {
&[_, _, .., _] => println!("slice has length at least 3"),
_ => (),
}
But you can't constrain its maximum length without an if
guard (that exhaustiveness checking doesn't understand). And if the length you want to check for is large, the syntax becomes unwieldy:
match slice {
&[_, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _] => println!("slice has length 21"),
_ => (),
}
To remedy this, the syntax for specifying array lengths could be adapted to work with slice patterns:
match slice {
&[..; 21] => println!("slice has length 21"),
_ => (),
}
match slice {
&[..; 13..=23] => println!("slice has length between 13 and 23"),
_ => (),
}
match slice {
&[.., 0; 13..=23] => println!("slice has length between 13 and 23, with last element 0")
_ => (),
}