Skip to content
Rust

메서드가 있는 구조체

Rust 구조체 정의 및 self와 Self로 메서드 구현.

#struct#method#intermediate

Code

rust
struct Rectangle {
    width: f64,
    height: f64,
}

impl Rectangle {
    fn new(width: f64, height: f64) -> Self {
        Rectangle { width, height }
    }

    fn area(&self) -> f64 {
        self.width * self.height
    }

    fn scale(&self, factor: f64) -> Rectangle {
        Rectangle::new(self.width * factor, self.height * factor)
    }
}

fn main() {
    let r = Rectangle::new(10.0, 5.0);
    println!("Area: {}", r.area());
    let big = r.scale(2.0);
    println!("Big area: {}", big.area());
}