Rust pattern matching over a vector
You need slice patterns:
fn vec_alt<T>(vals: Vec<T>) -> &'static str {
match vals[..] {
[a, b] => "two elements",
[a, b, c] => "three elements",
_ => "otherwise",
}
}
I wish I could give more general advice on how to best use pattern matching on vectors, but here's how you can use them to test for empty vectors (at least I think that's what that Haskell code is doing...):
use std;
import std::io::println;
fn main() {
let empty: [int] = [];
println(vec_alt(empty));
println(vec_alt([1,2,3]));
}
fn vec_alt<A>(vals: [A]) -> str {
alt vals {
x if x == [] { "empty" }
_ { "otherwise" }
}
}
Note that trying to simply pass []
as an argument fails because the compiler can't infer a type for the vector. It seems to be possible to pass [()]
(a vector with a nil
inside) without first declaring it, but the alt
statement seems incapable of testing to see if the head expression matches [()]
(it simply falls through to the default).
All in all, vectors seem a little rough at the moment. If there's some specific use you have in mind that Rust doesn't seem to support, the developers are quite open to suggestions and critcism: https://mail.mozilla.org/listinfo/rust-dev
Also see the reference manual for a more formal definition, and a few more examples to help clarify things: http://doc.rust-lang.org/doc/rust.html#alternative-expressions