Last active
January 2, 2025 14:57
-
-
Save decatur/355282b80e302e507bad14824381298c to your computer and use it in GitHub Desktop.
With Rust we do not just use Getters and Setters.
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
// Do not use Getter/Setter without immediate benefits, see also https://news.ycombinator.com/item?id=42506984 | |
// There are costs for abstraction and indirection. | |
// And in Rust, there is the borrow checker! | |
#[derive(Default)] | |
struct Strategy { | |
throughput: f64, | |
position: Vec<f64>, | |
} | |
impl Strategy { | |
fn throughput_mut(&mut self) -> &mut f64 { | |
return &mut self.throughput | |
} | |
} | |
#[derive(Default)] | |
struct Optimizer; | |
fn main() { | |
let mut strategy = Strategy::default(); | |
let position = strategy.position; | |
// Splitting borrows work on a field level | |
strategy.throughput += 2.; | |
// But does not work through GETTER! | |
// See https://stackoverflow.com/questions/67154204/how-to-borrow-two-disjoint-fields-when-the-borrow-is-behind-a-method-call | |
// let throughput = strategy.throughput_mut(); *throughput += 2.; | |
println!("{} {:?}", strategy.throughput, position); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment