Skip to content

Latest commit

 

History

History
43 lines (36 loc) · 812 Bytes

File metadata and controls

43 lines (36 loc) · 812 Bytes

Methods

When we declare a Rust structure, we can use an impl block to define some methods such as getters and setters.

/// x and y are private to Fred.
pub struct Fred {
    x: i32,
    y: String.
}

impl Fred {
    /// This getter is simple as `i32` is `Copy`
    pub fn x(&self) -> i32 {
        self.x
    }

    /// This getter uses a string slice which is cheap.
    pub fn y(&self) -> &str {
        self.y.as_str()
    }

    /// This is a setter, hence `&mut self`
    pub fn set_x(&mut self, x: i32) {
        self.x = x;
    }
}

We can also make associated functions which have no self. new is not a special word in Rust but a convention.

impl Fred {
    pub fn new() -> Self {
        Self {
            x: 1,
            y: "hello".to_owned(),
        }
    }
}