In my book Advanced Java Game Programming, I have a sidebar recommending named notation as a work-around for the Java programming language not supporting named arguments. Here is the example from the book as converted to the Rust programming language:
let game_data = SerializableGameData::new(
10, // health
99, // wealth
18); // wisdom
There is a proposal to bring named arguments to Rust but until this proposal is adopted I have started using a new work-around which I am calling "zero arguments methods". Here is a static function to be converted:
pub fn periodic_savings_needed(
f: f64,
r: f64,
t: f64,
) -> f64 {
f * r / ((1.0 + r).powf(t) - 1.0)
}
Here is the equivalent using a zero arguments method:
#[derive(Clone, Copy, Debug)]
pub struct PeriodicSavingsNeeded {
pub future_value: f64,
pub interest_rate: f64,
pub time_periods: f64,
}
impl PeriodicSavingsNeeded {
pub fn calculate(&self) -> f64 {
let f = self.future_value;
let r = self.interest_rate;
let t = self.time_periods;
f * r / ((1.0 + r).powf(t) - 1.0)
}
}
Here is how the zero arguments method can be called:
let calculated_value = PeriodicSavingsNeeded {
future_value: 1_000_000.0,
interest_rate: 0.12,
time_periods: 10.0,
}.calculate();
No comments:
Post a Comment