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() -> Self returns a fully charged battery (charge of 100).
  • with_charge(charge: u8) -> Self returns a battery with that charge, but never more than 100 (clamp larger values to 100).
  • drain(&mut self, amount: u8) lowers the charge by amount, stopping at 0 instead of underflowing. saturating_sub is useful here.

Use Self rather than Battery in the constructors.

Next lesson →

Sign in to run your code. It's free.