Rust Collections
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fn main() { | |
//The vec! macro is sugar for inline Vec<T> building | |
let vec1 = vec!["a", "b", "c"]; | |
let vec2 = vec![1, 2, 3]; | |
//Rust has iterators, which are usually cheaper than looping | |
for (&x, &y) in vec1.iter().zip(vec2.iter()) { | |
println!("{}, {}", x, y); | |
} | |
println!(""); | |
//You can iterate over more than just vectors | |
for i in 0..10 { | |
println!("{}", i); | |
} | |
println!(""); | |
//You can filter and map too (could use filter_map) | |
//Those '|'s are a closure. Rust functions have their own types; Fn, FnOnce and FnMut | |
for i in (0..10) | |
.filter(|i| i % 2 == 0) | |
.map(|i| i * 2) { | |
println!("{}", i); | |
} | |
//Other collection types include: | |
// - arrays (the size is part of the type) | |
// - BTreeSet / BTreeMap for ordered collections | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment