Reputation: 39
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");
| ^^^^^^^^
Upvotes: 3
Views: 5221
Reputation: 21
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();
Upvotes: 2
Reputation: 431089
I'm assuming it's because I shadow
answer
trimming it
Yes. String::trim
returns a &str
:
pub fn trim(&self) -> &str
&str
does not have the push_str
method.
See also:
Upvotes: 2