MĂ©todos
MĂ©todos sĂŁo funçÔes associadas a um tipo especĂfico. O primeiro argumento (self
) de um método é uma instùncia do tipo ao qual estå associado:
struct Rectangle { width: u32, height: u32, } impl Rectangle { fn area(&self) -> u32 { self.width * self.height } fn inc_width(&mut self, delta: u32) { self.width += delta; } } fn main() { let mut rect = Rectangle { width: 10, height: 5 }; println!("area antiga: {}", rect.area()); rect.inc_width(5); println!("nova area: {}", rect.area()); }
- Veremos muito mais sobre mĂ©todos no exercĂcio de hoje e na aula de amanhĂŁ.
-
Add a static method called
Rectangle::new
and call this frommain
:fn new(width: u32, height: u32) -> Rectangle { Rectangle { width, height } }
-
While technically, Rust does not have custom constructors, static methods are commonly used to initialize structs (but donât have to). The actual constructor,
Rectangle { width, height }
, could be called directly. See the Rustnomicon. -
Add a
Rectangle::square(width: u32)
constructor to illustrate that such static methods can take arbitrary parameters.