I keep getting this error. I'm assuming it's because I shadow answer trimming it since when I comment that part out I don't get the error anymore. I don't understand why that is.
fn main() {
let mut answer = String::new();
let num = 40;
if num % 2 == 0 {
answer.push_str("fact2 ");
}
if num % 5 == 0 {
answer.push_str("fact5 ");
}
let answer = answer.trim();
answer.push_str("bob was here");
println!("{}", answer);
}
error[E0599]: no method named `push_str` found for type `&str` in the current scope
--> src/main.rs:13:12
|
13 | answer.push_str("bob was here");
| ^^^^^^^^
I'm assuming it's because I shadow
answertrimming it
Yes. String::trim returns a &str:
pub fn trim(&self) -> &str
&str does not have the push_str method.
See also:
You're right, let answer = answer.trim(); is the problem. It sets answer to have type &str, and that push_str is defined for a mutable String.
You can fix it by changing that line to:
answer = answer.trim().to_string();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With