Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No method named `push_str` found for type `&str` after trimming a string

Tags:

scope

rust

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");
   |            ^^^^^^^^
like image 524
Ckiller Avatar asked Nov 25 '25 11:11

Ckiller


2 Answers

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:

  • Why does `name = *name.trim();` give me `expected struct `std::string::String`, found str`?
  • Efficient trimming of a String
  • How to "crop" characters off the beginning of a string in Rust?
like image 157
Shepmaster Avatar answered Nov 28 '25 16:11

Shepmaster


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();
like image 30
user3637260 Avatar answered Nov 28 '25 15:11

user3637260



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!