Rust 中如何定义类
1. Rust 定义类成员变量
利用结构体(struct)定义成员变量
// 利用结构体定义成员变量
struct Fruit {
color: String,
weight: f32
}
2. Rust 定义类成员方法
利用impl关键字来定义结构体成员方法
// 利用impl关键字来定义结构体成员方法
impl Fruit {
fn printInfo(&self) {
println!("{},{}",self.color,self.weight);
}
}
3. 完整代码
// 利用结构体定义成员变量
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();
}
问题来了,一般定义类前面都会有个关键字new,那么这个该怎么实现呢?看下面的例子。
Rust 定义标准类
// 利用结构体定义成员变量
struct Fruit {
color: String,
weight: f32
}
// 利用impl关键字来定义结构体成员方法
impl Fruit {
// 相当于方法Fruit::new()调用
fn new(color: String, weight:f32) -> Fruit {
Fruit {
color: color,
weight: weight
}
}
fn printInfo(&self) {
println!("{},{}",self.color,self.weight);
}
}
// 调用
fn main() {
let f = Fruit::new(String::from("green"), 12.5);
f.printInfo();
}
为什么在定义类方法printInfo(&self)里面传的参数是&self ?
解释:
- impl关键字在struct、enum或者trait对象上实现方法调用语法
- 关联函数 (associated function) 的第一个参数通常为self参数。
有几种变体:
- self,允许实现者移动和修改对象,对应的闭包特性为FnOnce
- &self,既不允许实现者移动对象也不允许修改,对应的闭包特性为Fn
- &mut self,允许实现者修改对象但不允许移动,对应的闭包特性为FnMut
- 不含self参数的关联函数称为静态方法 (static method)
Rust 定义接口
利用trait关键字定义一个接口:
// 接口
trait Area {
fn area(&self) -> f64;
}
利用struct定义一个类:
// 具体类
struct Circle {
r: f64
}
让【具体类】实现【接口】:
impl Area for Circle {
fn area(&self) -> f64 {
(3.14 * self.r) // 作为返回值 => 必须使用 () 括起来,并不能写 ;
}
}
完整代码:
// 接口
trait Area {
fn area(&self) -> f64;
}
// 具体类
struct Circle {
r: f64
}
// 让【具体类】实现【接口】
impl Area for Circle {
fn area(&self) -> f64 {
(3.14 * self.r) // 作为返回值 => 必须使用 () 括起来,并不能写 ;
}
}
fn main()
{
let r = Circle {r:10.5};
println!("area = {:?}", r.area());
}
impl Struct ...
与impl Trait for Struct ...
的区别
impl Struct ...
adds some methods to Struct
. These methods aren’t available to other types or traits.
impl Trait for Struct ...
implements the trait Trait
for the struct Struct
. This results in the methods of the trait being available for Struct
.
So, even though these two syntaxes look similar, they do 2 completely different things. impl Struct ...
adds new (not previously defined) methods to the type, while the other adds previously defined methods (from the trait) to the type.
相关内容:
rust 面向对象之Struct、impl、trait关键字使用
Impl trait for T 的作用
https://stackoverflow.com/questions/65977255/what-does-impl-for-mean