Rust 12: 面向对象详解(struct + impl + trait)

文章目录

      • struct
      • impl
      • trait
      • 扩展阅读
      • 总结

struct关键字用于定义一个数据结构,可以类比为面向对象语言中的class
impl关键字可以为struct实现关联的成员方法。
trait(特征)是对公共行为的抽象,类比面向对象语言中的接口。

struct

来定义一个“银行账户”的结构(类),包含账户ID和余额2个字段。

struct BankAccount {
    id: u64, 
    balance: i64,
}

impl

“银行账户”支持新建、存款、取款、转账等操作,我们用implBankAccount 结构关联这些方法实现。

// 定义“银行账户”支持的操作:新建、存款、取款、转账
impl BankAccount {
    //新建一个余额为0的账户,“静态”方法
    pub fn new(id: u64) -> Self {
        Self {
            id, //如果结构中字段名称,和初始化的变量名称相同,可以简写
            balance: 0i64,
        }
    }

    // 成员方法,存入
    pub fn deposit(&mut self, amount: u32) {
        self.balance += amount as i64;
    }

    // 成员方法,取出
    pub fn withdraw(&mut self, amount: u32) {
        self.balance -= amount as i64;
    }

    // 成员方法,对target账户转账
    pub fn transfer(&mut self, target: &mut BankAccount, amount: u32) -> bool {
        let amount = amount as i64;
        if self.balance >= amount {
            self.balance -= amount;
            target.balance += amount;
            true
        } else {
            false
        }
    }
}

其中,new(id)可以理解为是一个静态方法,可以直接通过BankAccount::new(id)进行调用。
其他几个方法,第一个参数是self或者&self,是为BankAccount对象实现的方法。

let mut ba1 = BankAccount::new(1);
let mut ba2 = BankAccount::new(2);
ba1.deposit(100_0000);
ba1.withdraw(10_0000);
ba1.transfer(&mut ba2, 30_0000);
assert_eq!(ba1.balance, 60_0000);
assert_eq!(ba2.balance, 30_0000);

trait

先来看一个标准库中定义的Debug trait

pub trait Debug {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result;
}

Debug trait中定义了一个需要实现的fmt()方法。凡事实现了Debug trait的结构都可以通过format!println!进行格式化。
为了让我们的BankAccount能够被println!打印出来,需要给BankAccount实现Debug trait

// 让BankAccount对象可以被println!打印出来
impl std::fmt::Debug for BankAccount {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "BankAccount({}, {})", self.id, self.balance)?;
        Ok(())
    }
}
println!("{:?}", BankAccount::new(3));//BankAccount(3, 0)

扩展阅读

关于如何给标准库中的String类型实现自己的trait:Rust如何修改字符串String中的字符
关于?操作符的的详细介绍:Rust问号?操作符
Rust格式化参数详解:Rust格式化输出:println、format格式化参数详解

总结

虽然严格来说,Rust并不是一门面向对象的编程语言,但是通过struct+impl+trait关键字组合,能够模拟出强大的面向对象能力。

你可能感兴趣的:(Rust编程:从0到100,rust,struct,rust面向对象,rust,impl关键字,rust,trait,impl,struct)