Rust Fundamentals · 15 XP Pro
Associated functions
Functions inside an impl block that do not take self are called
associated functions. You call them with :: on the type name, like
String::new(). They are most often used as constructors, and by convention the
main one is called new.
Inside an impl, Self is an alias for the type being implemented, so you do
not have to repeat its name:
pub struct Dice { pub sides: u8 }
impl Dice {
pub fn new() -> Self {
Self { sides: 6 }
}
pub fn with_sides(sides: u8) -> Self {
Self { sides }
}
}
let d = Dice::with_sides(20);
Constructors are a good place to enforce rules, such as clamping a value into a valid range.
Your task
The Battery struct is given, and its fields and methods must stay pub. Fill
in three items in impl Battery:
new() -> Selfreturns a fully charged battery (chargeof100).with_charge(charge: u8) -> Selfreturns a battery with that charge, but never more than100(clamp larger values to100).drain(&mut self, amount: u8)lowers the charge byamount, stopping at0instead of underflowing.saturating_subis useful here.
Use Self rather than Battery in the constructors.