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 Retangulo { largura: u32, altura: u32, } impl Retangulo { fn area(&self) -> u32 { self.largura * self.altura } fn aum_largura(&mut self, delta: u32) { self.largura += delta; } } fn main() { let mut ret = Retangulo { largura: 10, altura: 5 }; println!("area antiga: {}", ret.area()); ret.aum_largura(5); println!("nova area: {}", ret.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.