Rust: Function on Types (impl)
Status: Courses
-
Types like
structandenumscan have functions & methods attached to them usingimpl.// define struct struct Player { name: String, iq: u8, friends: u8, score: u16 } // define impl impl Player { // Initialize with Name fn with_name(name: &str) -> Player { Player { name: name.to_string(), iq: 100, friends: 100, score: 100 } } // Get friends field fn get_friends(&self) -> u8 { self.friends } } fn main() { // Init with name let player1 = Player::with_name("Joe"); // Get the friends field let player1_friends = player1.get_friends(); // Get the friends field another way. let player1_friend2 = Player::get_friends(&player); } -
In
implblock, there can be 2 types of functions- With
selftype as the first parameter - Instance Methods- The Instance Method can only be called on the existing variable of type. For ex: ****the ****
get_friendsfunction in the above code. - Instance Methods also have 3 variants
selfas the first parameter - Calling this method will consume the type, you cannot use the type anymore.&selfas the first parameter - Provides read-only access toself&mut selfas the first parameter - Provides mutable access toself
- The Instance Method can only be called on the existing variable of type. For ex: ****the ****
- Without
selftype as the first parameter - Associated Methods- Associated Methods don't require existing variables of the type. For ex: ****the ****
with_namefunction in the above code.
- Associated Methods don't require existing variables of the type. For ex: ****the ****
- With