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 @   咕咚!  阅读(113)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
历史上的今天:
2018-07-25 socket&socketserver网络编程
2018-07-25 collections模块
点击右上角即可分享
微信分享提示