rust学习笔记之小练习:泛型、trait

泛型

struct Wrapper<T> {
    value: T,
}

impl<T> Wrapper<T> {
    pub fn new(value: T) -> Self {
        Wrapper { value }
    }
}

fn main(){
    assert_eq!(Wrapper::new(42).value, 42);
    assert_eq!(Wrapper::new("Foo").value, "Foo");
}

trait

trait AppendBar {
    fn append_bar(self) -> Self;
}

impl AppendBar for String {
    fn append_bar(mut self) -> Self{
        self.push_str("Bar");
        self
    }
}

impl AppendBar for Vec<String> {
    fn append_bar(mut self) -> Self{
        self.push(String::from("Bar"));
        self
    }
}

fn main(){
    assert_eq!(String::from("Foo").append_bar(), String::from("FooBar"));
    assert_eq!(String::from("").append_bar().append_bar(),String::from("BarBar"));
    
    let mut foo = vec![String::from("Foo")].append_bar();
    assert_eq!(foo.pop().unwrap(), String::from("Bar"));
    assert_eq!(foo.pop().unwrap(), String::from("Foo"));
}

练习2

pub trait Licensed {
    fn licensing_info(&self) -> String{
        String::from("Some information")
    }
}

struct SomeSoftware {
    version_number: i32,
}

struct OtherSoftware {
    version_number: String,
}

impl Licensed for SomeSoftware {} 
impl Licensed for OtherSoftware {}

fn main(){
    let licensing_info = String::from("Some information");
    let some_software = SomeSoftware { version_number: 1 };
    let other_software = OtherSoftware {version_number: "v2.0.0".to_string()};
    assert_eq!(some_software.licensing_info(), licensing_info);
    assert_eq!(other_software.licensing_info(), licensing_info);
}
posted @ 2025-08-14 17:20  carol2014  阅读(7)  评论(0)    收藏  举报