Day 25
Feelings
Part 1 ➟ Looks like modular exponent, I hope part 2 isn't too bad. Part 2 ➟ Thank you Eric! \o/
It's been awesome journey through all these 25 days. I've learned a whole lot about Rust (and written tiny fraction about it here).
I'm hoping to do this again next year, but since the previous years are running there also.. Maybe.. Just maybe. =D
I also just donated to Advent of Code. I hope you will too.
Learnings
Cell
I haven't really wanted to touch many things (Rc, Arc, Box, Cell, RefCell, etc..) in Rust if I can manage without. This time I did want to take something extra. Today was easy. =)
So to Key calculates the secret loop count and I wanted it only calculated once. Without mutable internals every call to any method would result into mutable borrow like this.
struct Key {
public: usize,
loop_size: Option<usize>
}
impl Key {
// some details hidden here
fn get_secret(&mut self) -> usize {
if self.loop_size.is_none() {
// calculate s
self.loop_size = Some(s);
}
self.loop_size.unwrap()
}
}
And every time you'd want to use that:
let mut key = Key::new(5764801);
dbg!(
key.get_secret()
// ^^^^^^^^^^ and this now makes a mutable borrow
// even if it doesn't exactly look like it
);
So, it's dangerous to go alone - Take this: Cell.
Changing the struct is easy:
struct Key {
public: usize,
loop_size: Cell<Option<usize>>
}
And having that makes this pretty easy too:
fn get_secret(&self) -> usize {
if self.loop_size.get().is_none() {
// calculate s
self.loop_size.set(Some(s));
}
self.loop_size.get().unwrap()
}
After that, this is fine now:
// look mom, no mut
let key = Key::new(5764801);
dbg!(
key.get_secret()
);