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”, } }
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”, } }
Note: Typestate was dropped from Rust, only a limited version (tracking uninitialized and moved from variables) is left. See my note at the end. The motivation behind TypeState is that types are immutable, however some of their properties are dynamic, on a per variable basis. The idea is therefore to create simple predicates about a … Read more
This generates a random number between 0 (inclusive) and 100 (exclusive) using Rng::gen_range: use rand::Rng; // 0.8.5 fn main() { // Generate random number in the range [0, 99] let num = rand::thread_rng().gen_range(0..100); println!(“{}”, num); } Don’t forget to add the rand dependency to Cargo.toml: [dependencies] rand = “0.8”
Use char::to_string, which is from the ToString trait: fn main() { let string = ‘c’.to_string(); // or println!(“{}”, ‘c’); }