method
e.g.
.push_str("") - Ā Appends a string slice (&str) to the end of aĀ String.
.len() - Calculate lentgh of a collection, returning the number of elements or bytes it contains as a usize value.
from The Rust Programming Language
Methods are similar to functions: We declare them with theĀ fnĀ keyword and a name, they can have parameters and a return value, and they contain some code thatās run when the method is called from somewhere else. Unlike functions, methods are defined within the context of a struct (or an enum or a trait object, which we cover inĀ Chapter 6Ā andĀ Chapter 18, respectively), and their first parameter is alwaysĀ self, which represents the instance of the struct the method is being called on.
...
The main reason for using methods instead of functions, in addition to providing method syntax and not having to repeat the type ofĀ selfĀ in every methodās signature, is for organization. Weāve put all the things we can do with an instance of a type in oneĀ implĀ block rather than making future users of our code search for capabilities ofĀ RectangleĀ in various places in the library we provide.
impl
Implementations of functionality for a type, or a type implementing some functionality.
There are two uses of the keywordĀ impl:
- AnĀ
implĀ block is an item that is used to implement some functionality for a type. - AnĀ
impl TraitĀ in a type-position can be used to designate a type that implements a trait calledĀTrait.
Implementing Functionality for a Type
TheĀ implĀ keyword is primarily used to define implementations on types. Inherent implementations are standalone, while trait implementations are used to implement traits for types, or other traits.
An implementation consists of definitions of functions and consts. A function defined in anĀ implĀ block can be standalone, meaning it would be called likeĀ Vec::new(). If the function takesĀ self,Ā &self, orĀ &mut selfĀ as its first argument, it can also be called using method-call syntax, a familiar feature to any object-oriented programmer, likeĀ vec.len().
Example
struct Example {
number: i32,
}
impl Example {
fn boo() {
println!("boo! Example::boo() was called!");
}
fn answer(&mut self) {
self.number += 42;
}
fn get_number(&self) -> i32 {
self.number
}
}