Rust之impl关键字

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 ?

解释:

  1. impl关键字在struct、enum或者trait对象上实现方法调用语法
  2. 关联函数 (associated function) 的第一个参数通常为self参数。

有几种变体:

  1. self,允许实现者移动和修改对象,对应的闭包特性为FnOnce
  2. &self,既不允许实现者移动对象也不允许修改,对应的闭包特性为Fn
  3. &mut self,允许实现者修改对象但不允许移动,对应的闭包特性为FnMut
  4. 不含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

### 如何在 Rust 中为结构体实现方法 在 Rust 中,可以使用 `impl` 关键字为结构体定义关联函数和方法。下面是一个简单的例子展示如何创建一个带有字段的结构体并为其添加方法。 #### 定义带字段的结构体 ```rust #[derive(Debug)] struct Rectangle { width: u32, height: u32, } ``` #### 使用 impl 实现方法 通过 `impl` 块来声明属于该特定数据类型的函数: ```rust impl Rectangle { // 方法签名前加上 &self 表明这是一个实例方法 fn area(&self) -> u32 { self.width * self.height } // 可变借用允许修改调用者的数据成员 fn set_width(&mut self, new_width: u32) { self.width = new_width; } // 不接收任何参数的方法称为关联函数(类似于构造器) fn square(size: u32) -> Rectangle { Rectangle { width: size, height: size } } } fn main() { let rect1 = Rectangle { width: 30, height: 50 }; println!("The area of the rectangle is {} square pixels.", rect1.area()); let mut rect2 = Rectangle::square(40); rect2.set_width(70); println!("{:#?}", rect2); } ``` 上述代码展示了三种不同类型的方法:获取面积的只读访问方法、设置宽度的可写访问方法以及用于初始化正方形矩形的静态工厂方法[^1]。 对于更复杂的逻辑或者当需要多个特性时,还可以利用特征(trait)机制进一步扩展功能[^2]。 此外,在某些情况下,如果希望操作多种不同的具体类型,则可以通过动态分发的方式处理这些情况,比如使用 trait 对象作为容器中的元素类型[^3]。 最后值得注意的是,除了基本语法外,理解作用域解析运算符(::),可以帮助更好地探索泛型函数和其他高级概念[^4]。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值