美文网首页RUST编程
Rust 编程视频教程(进阶)——026_1 高级 trait1

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

作者: 令狐壹冲 | 来源:发表于2020-03-07 09:38 被阅读0次

视频地址

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

源码地址

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

讲解内容

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的时候必须带上具体的类型,调用时也必须带上具体的类型。

相关文章

网友评论

    本文标题:Rust 编程视频教程(进阶)——026_1 高级 trait1

    本文链接:https://www.haomeiwen.com/subject/irtqdhtx.html