Trait

Rust Trait

什么是 Trait

PHP trait

摘自php.nettrait 的介绍:

PHP 实现了一种代码复用的方法,称为 trait。

Trait 是为类似 PHP 的单继承语言而准备的一种代码复用机制。Trait 为了减少单继承语言的限制,使开发人员能够自由地在不同层次结构内独立的类中复用 method。Trait 和 Class 组合的语义定义了一种减少复杂性的方式,避免传统多继承和 Mixin 类相关典型问题。

Trait 和 Class 相似,但仅仅旨在用细粒度和一致的方式来组合功能。 无法通过 trait 自身来实例化。它为传统继承增加了水平特性的组合;也就是说,应用的几个 Class 之间不需要继承。

PHP Trait 示例:

/**
 * Trait Animal
 * 动物特型
 */
trait Animal {
    /**
     * 无法定义常量,使用变量代替
     * 物种
     * @var string 
     */
    private $SPECIES = "";

    /**
     * 抽象方法
     * 获取名称方法
     * @return string
     */
    abstract function name() :string;

    /**
     * 默认实现方法
     * 自我介绍方法
     * @return string
     */
    function say() :string {
        $name = $this->name();
        return "你好,我是一只{$this->SPECIES},我的名字叫\"{$name}\"";
    }
}

Rust trait

摘自rust语言官网trait 的介绍:

trait 告诉 Rust 编译器某个特定类型拥有可能与其他类型共享的功能。可以通过 trait 以一种抽象的方式定义共享的行为。可以使用 trait bounds 指定泛型是任何拥有特定行为的类型。

注意:trait 类似于其他语言中的常被称为 接口(interfaces)的功能,虽然有一些不同。

这里【其他语言】应该不包括PHP,因为PHP也有trait。

简单来说,Rust Trait 是通过 trait 关键字定义的一组方法(function)、类型(type)、常量(constant),实现代码复用。与 PHP trait 类似,PHP Trait 没有 typeconstant,但是可以定义变量(field)。

Rust Trait 示例:

/// 动物特型
trait Animal {
    /// 类型
    /// 错误类型
    type Err;

    /// 常量
    /// 物种名称
    const SPECIES: &'static str;

    /// 抽象方法
    /// 获取名称方法
    fn name(&self) -> &str;

    /// 默认实现方法
    /// 自我介绍方法
    fn say(&self) -> String {
        format!(r#"你好,我是一只{},我的名字叫"{}""#, Self::SPECIES, self.name())
    }
}

Trait 的实现

derive 宏

通过 derive 宏实现 trait,前提是已经定义了对应的proc_macro_derive宏方法,且内部类型都已经实现了该 trait。

/// Debug derive 宏核心库已经定义
/// 内部的 `name`(String)、`age`(u32) 都已经实现了 Debug trait,所以可以直接通过 derive 自动实现 Debug trait
#[derive(Debug)]
struct Bird {
    name: String
    age: u32
}

手动实现

impl trait name for struct or enum {}

/// 鸟是动物
impl Animal for Bird {
    type Err = ();
    const SPECIES: &'static str = "鸟";

    fn name(&self) -> &str {
        self.name.as_str()
    }
}

孤儿规则

当你为某类型实现某 trait 的时候,该类型或者trait至少有一个是在当前 crate 中定义的,不能为第三方的类型实现第三方的 trait 。否则可能会影响第三方 crate 中的行为。

Rust Trait 用途

在PHP中,trait 主要是解决 class 单继承的限制,但 Rust 中没有class 和继承的概念,也就没有这方面的用途。Rust Trait 用途主要有以下几个:

接口抽象

这个作用与 PHP trait 一样,但是PHP有专门的定义接口(interface)的功能;

/**
 * PHP 接口抽象 trait 形式
 */
trait Fly {
    /**
     * @throws Exception
     */
    function fly();
}

/**
 * PHP 接口抽象 interface 形式
 */
interface Fly {
    /**
     * @throws Exception
     */
    function fly();
}
/// Rust 接口抽象
/// 定义一个 `Fly` 接口
trait Fly {
    fn fly() -> Result<(), ()>;
}

/// 鸟能飞,实现 Fly 接口
impl Fly for Bird {
    fn fly(&self) -> Result<(), ()> {
        println!("芜湖起飞");
        Ok(())
    }
}


泛型约束

rust:

/// 定一个一个动物飞行方法
/// 一边飞一边自我介绍
/// 参数 flyer 类型为泛型参数T,T 约束为:需要同时实现 `Fly` trait 和 `Animal` trait
fn animal_fly<T: Fly + Animal>(flyer: T) {
    // fly 函数来自 `Fly` trait
    flyer.fly();
    // say 函数来自 `Animal` trait
    println!("{},我正在天空翱翔", flyer.say())
}

PHP 中没有泛型,PHP 8 的 Union Types 是或(“|”)的关系,而不是且的关系。

方法重载

方法重载是指在一个类中定义多个同名的方法,但要求每个方法具有不同的参数的类型或参数的个数。在 Java 中,可以在 class 中直接定义多个重载方法。rust 中,无法为结构体定义重载方法,但是可以借助 trait 实现。

例如:i64from 方法,是通过核心库的 From<T> trait 实现的
在这里插入图片描述

/// 给 `Bird` 声明 `from` 创建对象方法
impl Bird {
    fn from(name: &str) -> Self {
        Bird {
            name: name.to_string()
        }
    }
}
/// 通过 `From<T>` trait 重载 from 方法
/// 通过编号(u32)创建对象
impl From<u32> for Bird {
    fn from(num: u32) -> Self {
        Bird {
            name: format!("小{}", num)
        }
    }
}
/// 通过名称(String)创建对象
impl From<String> for Bird {
    fn from(name: String) -> Self {
        Bird {
            name
        }
    }
}

这样 Bird 也有几个 from 重载方法了,rust 会根据参数类型选择调用对应的方法

常用 Trait

Display

打印对象信息

use std::fmt::{Display, Formatter};

struct Pig {
    name: String
}

impl Display for Pig {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "这只小猪是:{}", self.name)
    }
}

fn main() {
    let bird = Pig { name: "佩奇".to_string() };
    println!("{}", bird); // 这只小猪是:佩奇
}

Debug

打印对象 Debug 信息

#[derive(Debug)]
struct Pig {
    name: String
}

fn main() {
    let bird = Bird { name: "佩奇".to_string() };
    println!("{:?}", bird); // Pig { name: "佩奇" }
}

Clone

#[derive(Clone)]
struct Sheep {
    name: String
}
fn main() {
    let sheep1 = Sheep {  name: "Dolly".to_string() };
    // 所有权发生转移,pig1 变成未定义
    let sheep2 = sheep1;
    // 报错
    println!("sheep1 是 {}", sheep1.name);
    

    // 调用 Clone Trait 的 clone 函数克隆羊,sheep2 依然存在
    let sheep3 = sheep2.clone();
    println!("sheep2 是 {}", sheep2.name);
    println!("sheep3 是 {}", sheep3.name);
}

Copy

/// 实现 Copy trait 需要同时实现 Clone
#[derive(Clone, Copy)]
struct Int(i64);

fn main() {
    let int1 = Int(1);
    // 不发生所有权转移,自动复制
    let int2 = int1;
    println!("int1: {}", int1.0);
    println!("int2: {}", int2.0);
}

From / Into

/// 为 Int 实现 From<i32>
impl From<i32> for Int {
    fn from(num: i32) -> Self {
        Int(i64::from(num))
    }
}

/// 为 Int 实现 Into<i32>
impl Into<i32> for Int {
    fn into(self) -> i32 {
        self.0 as i32
    }
}

fn main() {
    let int1 = Int::from(1_i32);
    let inner: i32 = int1.into();
    println!("int1: {}", int1.0);
    println!("inner: {}", inner);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值