I'm trying to write a trait on the String
type that will allow it to concatenate Bar
to any other string.
I know what the solution is but I'm not sure why it works. Could someone please explain the theory underlying the syntax for me?
// problematic code
// error[E0308]: mismatched types
// rustc --explain E0308
fn append_bar(self) -> String {
self + String::from("Bar")
}
// solution
fn append_bar(self) -> String {
self + &String::from("Bar")
}
The full script is below.
trait AppendBar {
fn append_bar(self) -> String;
}
impl AppendBar for String {
fn append_bar(self) -> String {
self + String::from("Bar")
}
}
fn main() {
let s = String::from("Foo");
let s = s.append_bar();
println!("s: {}", s);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn is_FooBar() {
assert_eq!(String::from("Foo").append_bar(), String::from("FooBar"));
}
#[test]
fn is_BarBar() {
assert_eq!(
String::from("").append_bar().append_bar(),
String::from("BarBar")
);
}
}