Rust 使用trait 来实现函数重载

fn main(){
    let hero = Hero::with("Apple".to_string());
    println!("{:#?}",hero);
    let hero2 = Hero::with(Sex::Gril);
    println!("{:#?}",hero2);
    let hero3 = Hero::with(32);
    println!("{:#?}",hero3);
    let hero4 = Hero::new();
    println!("{:#?}",hero4);
}

//定义一个泛型trait
pub trait With{
    fn with(value:T) -> Self;
}
#[derive(Debug)]
enum Sex{
    Boy,
    Gril,
}
#[derive(Debug)]
struct Hero{
    name:String,
    sex:Sex,
    age:i32
}

impl Default for Hero{
    fn default() -> Self{
        Hero{
            name: "NoName".to_string(),
            sex: Sex::Boy,
            age: 18i32
        }
    }

}

impl Hero{
    fn new()->Self{
        Hero
        {
            ..Default::default()
        }
    }
}
impl With for Hero{
    fn with(x:String) -> Self{
        Hero{
            name:x,
            ..Default::default()
        }
    }
}
impl With for Hero{
    fn with(x:Sex) -> Self{
        Hero{
            sex:x,
            ..Default::default()
        }
    }
}
impl With for Hero{
    fn with(x:i32) -> Self{
        Hero{
            age:x,
            ..Default::default()
        }
    }
}

你可能感兴趣的:(Rust,笔记)