Rust Impl是干嘛的

提问

Rust Impl是干嘛的

回答

拓展结构体让结构体具有函数

// 利用结构体定义成员变量
struct Fruit {
    color: String,
    weight: f32
}
// 利用impl关键字来定义结构体成员方法
impl Fruit {
    fn printInfo(&self) {
        println!("{},{}",self.color,self.weight);
    }
}
// 调用
fn main() {
    let f = Fruit{color:String::from("green"), weight:12.5};
    f.printInfo();
}

posted @ 2024-07-09 14:39  喜爱糖葫芦  阅读(4)  评论(0编辑  收藏  举报