Kodkitabi

Struct ve Metotlar

Veri gruplama ve bir Struct'a davranış (metot) ekleme.

Struct yapısı ile kendi özel veri tiplerimizi tanımlarız. Rust'ta metotlar, bir impl bloğu içerisinde tanımlanır ve &self parametresi ile o struct örneğine bağlanır.

Struct Tanımlama ve Metot Yazma
struct Rectangle {
    width: u32,
    height: u32,
}

impl Rectangle {
    // Metot: Alan hesaplama
    fn area(&self) -> u32 {
        self.width * self.height
    }
}

fn main() {
    let rect = Rectangle { width: 30, height: 50 };
    println!("Alan: {}", rect.area());
}