rust : wip.
This commit is contained in:
parent
2aa8e03572
commit
3cd93671e2
29
dev/lang/rust/hashmap.md
Normal file
29
dev/lang/rust/hashmap.md
Normal file
|
@ -0,0 +1,29 @@
|
||||||
|
# Hashmap.
|
||||||
|
|
||||||
|
# Create / Use.
|
||||||
|
|
||||||
|
```rust
|
||||||
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
// Create.
|
||||||
|
let mut scores = HashMap::new();
|
||||||
|
|
||||||
|
// Insert.
|
||||||
|
scores.insert(String::from("Blue"), 10);
|
||||||
|
scores.insert(String::from("Yellow"), 50);
|
||||||
|
|
||||||
|
// Get.
|
||||||
|
let team_name = String::from("Blue");
|
||||||
|
let score = scores.get(&team_name).copied().unwrap_or(0); // .get() returns Option<&i32> hence the .copied().
|
||||||
|
|
||||||
|
// Iterate.
|
||||||
|
for (key, value) in &scores {
|
||||||
|
println!("{key}: {value}");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update.
|
||||||
|
scores.insert(String::from("Blue"), 20); // Overwrite.
|
||||||
|
scores.entry(String::from("Blue")).or_insert(20); // Only if not exists.
|
||||||
|
let count = scores.entry(String::from("Blue")).or_insert(0);
|
||||||
|
*count += 1; // Add, substract etc.
|
||||||
|
```
|
|
@ -0,0 +1,68 @@
|
||||||
|
# Module (access control).
|
||||||
|
|
||||||
|
# Create module.
|
||||||
|
|
||||||
|
## Separate file.
|
||||||
|
|
||||||
|
`src/garden.rs`
|
||||||
|
|
||||||
|
## Separate dir.
|
||||||
|
|
||||||
|
`src/garden/mod.rs`
|
||||||
|
|
||||||
|
## Inline / Access control.
|
||||||
|
|
||||||
|
Everything is private by default. Use keyword `pub` to make something public.
|
||||||
|
|
||||||
|
```rust
|
||||||
|
mod sausage_factory {
|
||||||
|
fn get_secret_sauce() -> String {
|
||||||
|
String::from("Ginger")
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn make_sausage() {
|
||||||
|
get_secret_sauce();
|
||||||
|
println!("sausage!");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
sausage_factory::make_sausage();
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
# Access module.
|
||||||
|
|
||||||
|
Use `use` and `as` keywords.
|
||||||
|
|
||||||
|
```rust
|
||||||
|
use std::io;
|
||||||
|
use std::io as IO;
|
||||||
|
use std::io::{self, Write};
|
||||||
|
use std::collections::*;
|
||||||
|
```
|
||||||
|
|
||||||
|
```rust
|
||||||
|
mod delicious_snacks {
|
||||||
|
pub use self::fruits::PEAR as fruit;
|
||||||
|
pub use self::veggies::CUCUMBER as veggie;
|
||||||
|
|
||||||
|
mod fruits {
|
||||||
|
pub const PEAR: &'static str = "Pear";
|
||||||
|
pub const APPLE: &'static str = "Apple";
|
||||||
|
}
|
||||||
|
|
||||||
|
mod veggies {
|
||||||
|
pub const CUCUMBER: &'static str = "Cucumber";
|
||||||
|
pub const CARROT: &'static str = "Carrot";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
println!(
|
||||||
|
"favorite snacks: {} and {}",
|
||||||
|
delicious_snacks::fruit,
|
||||||
|
delicious_snacks::veggie
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
Loading…
Reference in a new issue