Rust基础06-结构体
Struct 实例
-
计算长方形面积
#[derive(Debug)] struct Rectangle { width: u32, length: u32, } fn main() { let rect = Rectangle { width: 30, length: 50, }; println!("{}", area(&rect)); println!("{:#?}", rect); } fn area(rect: &Rectangle) -> u32 { rect.width * rect.length }
在上述代码中,如果我们直接使用
println!("{}", rect);
来打印 Rectangle 实例,程序会报错,见下:error[E0277]: `Rectangle` doesn't implement `std::fmt::Display`
相关解释见图:
因此,我们在程序中使用
println!("{:#?}", rect);
来实现打印 Rectangle 实例,在程序第一行写下#[derive(Debug)]
相关解释见图:
更多相关信息见:
使用结构体的代码例子
Struct 方法
-
方法与函数
相似:fn 关键字、名称、参数、返回值
不同:- 方法是在 struct (或 enum、trait 对象) 的上下文中定义
- 第一个参数为 self,表示方法被调用的 struct 实例
-
定义方法:
在 impl 块中定义方法
方法的第一个参数可以是 &self,也可以获得其所有权 或 可变借用,与其他参数一样
//实例:长方体面积 #[derive(Debug)] struct Rectangle { width: u32, length: u32, } //定义方法 impl Rectangle { fn area(&self) -> u32 { self.width * self.length } } fn main() { let rect = Rectangle { width: 30, length: 50, }; println!("{}", rect.area()); println!("{:#?}", rect); }
-
方法调用运算符:
在 C/C++ 中,我们可以通过如下调用方法:
object -> something() (*object).something()
在 Rust 中,没有 -> 运算符,但 Rust 会自动引用或解引用
在调用方法时就会发生这种行为,Rust 根据情况自动添加 &、&mut 或 ,以便 object 可以匹配方法的签名
p1.distance(&p2); (&p1).distance(&p2);
-
关联函数:
可以在 impl 块中定义不把 self 作为第一个参数的函数,它们叫关联函数(不是方法)
如:String::from()
关联函数通常用于构造器
//实例:长方形体积->impl中定义的关联函数 fn square(size: u32) -> Rectangle { Rectangle { width: size, length: size } }
-
impl 块:
每个 struct 允许拥有多个 impl 块