Methods & Associated Functions in Rust

Methods & Associated Functions in Rust

Introduction

Methods are functions that are defined in the context of a struct.

#[derive(Debug)]
struct Player {
    player_name: String,
    pos_x: i32,
    pos_y: i32,
    hp: u16,
    is_alive: bool,
}

impl Player {
    fn health_check(self: &Self) -> String {
        if self.hp == 100 {
            "Full health.".to_string()
        } else {
            "Not full health.".to_string()
        }
    }
}

We use impl or implementation block to declare methods. Here we have one but we can also have multiple methods inside impl

We can also have multiple impl blocks, it may not be required but it's valid.

self in impl represents the struct itself, so in this case the Player. We can also write &self as a shorthand in place of self: &Self

Examples

Below is how we can use methods.

#[derive(Debug)]
struct Player {
    player_name: String,
    pos_x: i32,
    pos_y: i32,
    hp: u16,
    is_alive: bool,
}

impl Player {
    fn health_check(self: &Self) -> String {
        if self.hp == 100 {
            "Full health.".to_string()
        } else {
            "Not full health.".to_string()
        }
    }

    fn health_compare(self: &Self, player: &Player) -> String {
        let mut resp: String;
        if self.hp > player.hp {
            resp = format!("{} has more hp compared to {}", self.player_name, player.player_name);
        } else if self.hp < player.hp {
            resp = format!("{} has more hp compared to {}", player.player_name, self.player_name);
        } else {
            resp = format!("Both players have equal hp");
        }
        resp
    }
}

fn main() {
    let player1 = populate_struct(String::from("Prince Vegeta"), 50);
    let player2 = populate_struct(String::from("John Cena"), 50);

    println!("{:#?}", player1);
    println!("{:#?}", player2);

    println!("{}", player1.health_check());
    println!("{}", player2.health_check());

    println!("{}", player1.health_compare(&player2));
}

fn populate_struct(player_name: String, hp: u16) -> Player {
    Player {
        player_name,
        pos_x: 0,
        pos_y: 0,
        hp,
        is_alive: true
    }
}

Output:

Player {
    player_name: "Prince Vegeta",
    pos_x: 0,
    pos_y: 0,
    hp: 50,
    is_alive: true,
}
Player {
    player_name: "John Cena",
    pos_x: 0,
    pos_y: 0,
    hp: 50,
    is_alive: true,
}
Not full health.
Not full health.
Both players have equal hp

So we have a Player struct. Two players player1 & player2 are created out of it. And we have two methods health_check & health_compare inside impl

health_check simply checks the hp of the player and returns a String

health_compare takes another player as an argument and returns a String after comparing the health of both the players.

A practical scenario would be to perform some Game logic rather than returning a String, but I hope you get the idea how methods are used.

We'll surely build a Game also in the near future, after all Rust is also quite popular for making Games!

Conclusion

That's all about methods in Rust. Simple but effective!

We'll soon meet with another Rusty article. Cheers.