capypad
0 day streak
rust / beginner
Snippet

Importing Modules with the use Statement

The use statement brings items into scope, making code cleaner. You can import single items, or use nested paths with curly braces. The self keyword imports the module itself. Question mark operator (?) propagates errors from io::Result.

snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
use std::collections::HashMap;
use std::io::{self, Write};
 
fn main() -> io::Result<()> {
let mut scores: HashMap<&str, i32> = HashMap::new();
scores.insert("Alice", 95);
scores.insert("Bob", 87);
println!("Alice's score: {}", scores.get("Alice").unwrap_or(&0));
io::stdout().write_all(b"Done!\n")?;
Ok(())
}
Breakdown
1
use std::collections::HashMap;
Brings HashMap directly into scope
2
use std::io::{self, Write};
Imports io module and Write trait
3
HashMap::new()
Creates a new empty HashMap
4
scores.get("Alice").unwrap_or(&0)
Safely gets value, returns 0 if not found