traits1.rs (620B)
1 // The trait `AppendBar` has only one function which appends "Bar" to any object 2 // implementing this trait. 3 trait AppendBar { 4 fn append_bar(self) -> Self; 5 } 6 7 impl AppendBar for String { 8 fn append_bar(self) -> Self { 9 self + "Bar" 10 } 11 } 12 13 fn main() { 14 let s = String::from("Foo"); 15 let s = s.append_bar(); 16 println!("s: {s}"); 17 } 18 19 #[cfg(test)] 20 mod tests { 21 use super::*; 22 23 #[test] 24 fn is_foo_bar() { 25 assert_eq!(String::from("Foo").append_bar(), "FooBar"); 26 } 27 28 #[test] 29 fn is_bar_bar() { 30 assert_eq!(String::from("").append_bar().append_bar(), "BarBar"); 31 } 32 }