traits1.rs (686B)
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 // TODO: Implement `AppendBar` for the type `String`. 9 fn append_bar(self: String) -> Self { 10 self + "Bar" 11 } 12 } 13 14 fn main() { 15 let s = String::from("Foo"); 16 let s = s.append_bar(); 17 println!("s: {s}"); 18 } 19 20 #[cfg(test)] 21 mod tests { 22 use super::*; 23 24 #[test] 25 fn is_foo_bar() { 26 assert_eq!(String::from("Foo").append_bar(), "FooBar"); 27 } 28 29 #[test] 30 fn is_bar_bar() { 31 assert_eq!(String::from("").append_bar().append_bar(), "BarBar"); 32 } 33 }