rust-book/oop/src/lib.rs
2019-02-06 13:49:34 -05:00

46 lines
996 B
Rust

/// Example of encapsulation, as a
/// requirement of Object Oriented Programming.
///
/// The list property is private, eg, encapsulated,
/// while the object itself handles manipulation of
/// the list property.
pub struct AveragedCollection {
list: Vec<i32>,
average: f64,
}
impl AveragedCollection {
pub fn add(&mut self, value: i32) {
self.list.push(value);
self.update_average();
}
pub fn remove(&mut self) -> Option<i32> {
let result = self.list.pop();
match result {
Some(value) => {
self.update_average();
Some(value)
},
None => None,
}
}
pub fn average(&self) -> f64 {
self.average
}
fn update_average(&mut self) {
let total: i32 = self.list.iter().sum();
self.average = total as f64 / self.list.len() as f64;
}
}
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
assert_eq!(2 + 2, 4);
}
}