Rust 编程视频教程(进阶)——026_1 高级 trait1

视频地址

头条地址:https://www.ixigua.com/i677586170644791348...
B站地址:https://www.bilibili.com/video/av81202308/

源码地址

github地址:https://github.com/anonymousGiga/learn_rus...

讲解内容

1、关联类型在trait定义中指定占位符类型
关联类型是一个将类型占位符与trait相关论的方式。trait 的实现者会针对特定的实现在这个类型的位置指定相应的具体类型。如此可以定义一个使用多种类型的 trait。
(1)回忆使用关联类型的例子中,Iterator trait:

pub trait Iterator {
    type Item;
    fn next(&mut self) -> Option<Self::Item>;
}

(2)为什么不像如下,使用泛型?

pub trait Iterator<T> {
    fn next(&mut self) -> Option<T>;
}

如果使用泛型,实现的例子如下:

trait Iterator1<T> {
    fn next(&mut self) -> Option<T>;
}
struct A {
    value: i32,
}
impl Iterator1<i32> for A {
    fn next(&mut self) -> Option<i32> {
        println!("in next function: i32");
        if self.value > 3 {
            self.value += 1;
            Some(self.value)
        } else {
            None
        }
    }
}
impl Iterator1<String> for A {
    fn next(&mut self) -> Option<String> {
        println!("in next function: string");
        if self.value > 3 {
            let s = String::from("hello");
            Some(s)
        } else {
            None
        }
    }
}
fn main() {
    let mut a = A{value: 3};
    //a.next();   //错误,因为编译器不知道调用哪个实现
    <A as Iterator1<String>>::next(&mut a);      //完全限定语法,带上了具体的类型
    <A as Iterator1<i32>>::next(&mut a);         //完全限定语法,带上了具体的类型
    println!("Hello, world!");
}

说明:使用泛型的方式,则如例子中在实现trait的时候必须带上具体的类型,调用时也必须带上具体的类型。

本作品采用《CC 协议》,转载必须注明作者和本文链接
令狐一冲
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!
文章
255
粉丝
120
喜欢
308
收藏
128
排名:335
访问:2.8 万
私信
所有博文
社区赞助商