Rust基础-关于trait之二

Rust基础-关于trait之一_DarcyZ_SSM的博客-CSDN博客

上一篇写的比较乱一点,仅介绍了一些trait的常用用法,本篇整理一下。

trait的使用方式:

1、静态派发

struct Women;
impl Sound for Women {
    fn shout(&self) -> &str {
        "Harder!"
    }
}
fn shout_static(g: G) {
    println!("{}", g.shout());
}
shout_static(Women);

2、动态派发

struct Women;
impl Sound for Women {
    fn shout(&self) -> &str {
        "Harder!"
    }
}
fn shout_dynamic(g: Box) {
    println!("{}", g.shout());
}
shout_dynamic(Box::new(Women));

3、impl trait

struct Women;
impl Sound for Women {
    fn shout(&self) -> &str {
        "Harder!"
    }
}
fn shout_impl(g: impl Sound) {
    println!("{}", g.shout());
}
shout_impl(Women);

4、关联类型:是 trait 定义中的类型占位符。定义的时候,并不定义它的具体的类型是什么。在实现的时候,才知道它的具体类型是什么。

struct Women;
struct Girl;
impl Sound for Women {
    fn shout(&self) -> &str {
        "Harder!"
    }
}
impl Sound for Girl {
    fn shout(&self) -> &str {
        "Slow down!"
    }
}
trait Convert{
    type Tp;    //关联类型
    fn to_girl(&self)->Self::Tp;
}

impl Convert for Women{
    type Tp=Girl;
    fn to_girl(&self)->Self::Tp{
       Girl
    }
}
 let f=Women;
println!("{}",f.to_girl().shout());

5、泛型

struct Women;
struct Alien;
impl Sound for Women {
    fn shout(&self) -> &str {
        "Harder!"
    }
}
impl Sound for Alien{
    fn shout(&self) -> &str {
        "Bili Bili!"
    }
}
trait  Convert2 {
    fn to_alien(&self)->Option;//泛型
    
}

impl Convert2 for Women{
    fn to_alien(&self)->Option{
        Some(Alien)
    }
}
 let f=Women;
 println!("{}",f.to_alien().unwrap().shout());

下面是完整代码:

struct Women;
struct Girl;
struct Alien;
trait Sound {
    fn shout(&self) -> &str;
}
impl Sound for Women {
    fn shout(&self) -> &str {
        "Harder!"
    }
}
impl Sound for Girl {
    fn shout(&self) -> &str {
        "Slow down!"
    }
}
impl Sound for Alien{
    fn shout(&self) -> &str {
        "Bili Bili!"
    }
}

trait Convert{
    type Tp;    //关联类型
    fn to_girl(&self)->Self::Tp;
}

trait  Convert2 {
    fn to_alien(&self)->Option;//泛型
    
}
impl Convert for Women{
    type Tp=Girl;
    fn to_girl(&self)->Self::Tp{
       Girl
    }
}
impl Convert for Girl{
    type Tp=Women;
    fn to_girl(&self)->Self::Tp{
       Women
    }
}
impl Convert2 for Women{
    fn to_alien(&self)->Option{
        Some(Alien)
    }
}
//静态派发
fn shout_static(g: G) {
    println!("{}", g.shout());
}
//动态派发
fn shout_dynamic(g: Box) {
    println!("{}", g.shout());
}
//impl trait可以用在函数参数与返回值。
fn shout_impl(g: impl Sound) {
    println!("{}", g.shout());
}
fn main() {
    shout_static(Women);
    shout_dynamic(Box::new(Women));
    shout_impl(Women);
    let f=Women;
    println!("{}",f.to_girl().shout());
    println!("{}",f.to_alien().unwrap().shout());
   
}

相关文章:

Rust基础-关于trait之一_DarcyZ_SSM的博客-CSDN博客

 Rust基础-关于trait之三_DarcyZ_SSM的博客-CSDN博客

Rust基础-关于trait之四-不得不说一下rust fat point_DarcyZ_SSM的博客-CSDN博客

 Rust基础-关于trait之五_DarcyZ_SSM的博客-CSDN博客

 Rust基础-关于trait之六,动态派发和静态派发的区别

你可能感兴趣的:(rust,rust)