This year I will try to solve each puzzle in both Python and Rust.
- Read file (shorter way):
text = include_str!("input");
-
Convert
str
to numeric types:- Annotating the variable:
let x: u32 = "4".parse().unwrap();
- Using "turbofish":
let x = "4".parse::<u32>().unwrap();
-
Operations with iterators, including
sorted
,rev
,cartesian_product
, etc
[dependencies]
itertools = "0.10.5"
use itertools.Itertools;
Filtering values from a HashMap needs two de-references: values()
(or keys()
, items()
) return references so not to consume the map, and filter()
also doesn't consume its arguments:
use std::collections::HashMap;
let mut map: HashMap<String, u32> = HashMap::new();
//...
let total = map.values().filter(|x| **x > 0).sum();
Debugging Rust with the extension CodeLLDB.
- Implementing
From
to convert to a custom enum/struct
use std::convert::From;
struct MyStruct {
//...
}
impl MyStruct {
fn From<i32>(x: i32) -> Self {
//...
}
}
- Appending the content of a vector into other vector:
let mut v1 = vec![1, 2, 3];
let mut v2 = vec![4, 5, 6];
v1.append(&mut v2);
assert_eq![v1, vec![1, 2, 3, 4, 5, 6]];
assert_eq![v2, []];
Note that the copied vector needs to be passed as &mut
, as it will be emptied by append
.
-
Using
serde_json
to parse a list of values and store it in aValue
. -
impl
-ementing thePartialOrd
andOrd
traits to compare and sortstruct
s orenum
s.- Traits cannot be implemented in objects defined in a different file.
- Regex with the crate Regex.
- Syntax for
impl
-ementingDebug
orDisplay
: the macrowrite!
modifies theFormatter
object and returns afmt::Result
:
impl Display for MyStruct {
fn fmt(&self, f_ &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let s = String::new();
// ... obtain s
write!(f, "{}", s)
}
}
- Beware! Numerical overflows don't give a warning!