mirror of
https://github.com/rust-lang/rustlings.git
synced 2026-01-04 09:49:19 +00:00
finish traits exercises
This commit is contained in:
parent
2a9bd74176
commit
5a9d6a6677
@ -1,21 +1,22 @@
|
|||||||
// traits1.rs
|
// traits1.rs
|
||||||
// Time to implement some traits!
|
// Time to implement some traits!
|
||||||
//
|
//
|
||||||
// Your task is to implement the trait
|
// Your task is to implement the trait
|
||||||
// `AppendBar' for the type `String'.
|
// `AppendBar' for the type `String'.
|
||||||
//
|
//
|
||||||
// The trait AppendBar has only one function,
|
// The trait AppendBar has only one function,
|
||||||
// which appends "Bar" to any object
|
// which appends "Bar" to any object
|
||||||
// implementing this trait.
|
// implementing this trait.
|
||||||
|
|
||||||
// I AM NOT DONE
|
|
||||||
trait AppendBar {
|
trait AppendBar {
|
||||||
fn append_bar(self) -> Self;
|
fn append_bar(self) -> Self;
|
||||||
}
|
}
|
||||||
|
|
||||||
impl AppendBar for String {
|
impl AppendBar for String {
|
||||||
//Add your code here
|
fn append_bar(mut self) -> Self {
|
||||||
|
self.push_str("Bar");
|
||||||
|
self
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
@ -40,5 +41,4 @@ mod tests {
|
|||||||
String::from("BarBar")
|
String::from("BarBar")
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
}
|
|
||||||
|
|||||||
@ -1,25 +1,25 @@
|
|||||||
// traits2.rs
|
// traits2.rs
|
||||||
//
|
//
|
||||||
// Your task is to implement the trait
|
// Your task is to implement the trait
|
||||||
// `AppendBar' for a vector of strings.
|
// `AppendBar' for a vector of strings.
|
||||||
//
|
//
|
||||||
// To implement this trait, consider for
|
// To implement this trait, consider for
|
||||||
// a moment what it means to 'append "Bar"'
|
// a moment what it means to 'append "Bar"'
|
||||||
// to a vector of strings.
|
// to a vector of strings.
|
||||||
//
|
//
|
||||||
// No boiler plate code this time,
|
// No boiler plate code this time,
|
||||||
// you can do this!
|
// you can do this!
|
||||||
|
|
||||||
// I AM NOT DONE
|
|
||||||
|
|
||||||
trait AppendBar {
|
trait AppendBar {
|
||||||
fn append_bar(self) -> Self;
|
fn append_bar(self) -> Self;
|
||||||
}
|
}
|
||||||
|
|
||||||
//TODO: Add your code here
|
impl AppendBar for Vec<String> {
|
||||||
|
fn append_bar(mut self) -> Self {
|
||||||
|
self.push("Bar".to_string());
|
||||||
|
self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
@ -31,5 +31,4 @@ mod tests {
|
|||||||
assert_eq!(foo.pop().unwrap(), String::from("Bar"));
|
assert_eq!(foo.pop().unwrap(), String::from("Bar"));
|
||||||
assert_eq!(foo.pop().unwrap(), String::from("Foo"));
|
assert_eq!(foo.pop().unwrap(), String::from("Foo"));
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user