Skip to content
Justice Tech School

Struct Methods and Associated Functions

impl blocks add methods that take &self or &mut self and associated functions such as new that do not take self. Call methods with a dot and associated functions with ::.

Example
struct Counter { n: u32 }
impl Counter {
    fn new() -> Self { Counter { n: 0 } }
    fn inc(&mut self) -> &mut Self { self.n += 1; self }
    fn get(&self) -> u32 { self.n }
}
fn main() {
    let mut c = Counter::new();
    c.inc().inc();
    println!("{}", c.get());
}

Result

2

Exercise

Constructor name by convention.

fn () -> Self

Quiz Test

How do you call Counter::new?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.