rust关联函数

rust的关联函数很有Go中的interface感觉,鸭子类型的身影在里面。

#[derive(Debug)]
struct  Rectangle {
    width: u32,
    height: u32,
}

impl Rectangle {
    // Rectangle 方法的实现
    fn area(&self) -> u32 {
        self.height * self.width
    }

    // square 关联函数 实现有点鸭子类型的感觉。
    fn square(size: u32) -> Rectangle {
        Rectangle {
            width: size,
            height: size,
        }
    }
}

fn main() {
    let square = Rectangle::square(22);
    println!("{:?}", square)
}

posted @ 2022-07-25 11:26  咕咚!  阅读(118)  评论(0)    收藏  举报