Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a string by reference and manipulate the string

Tags:

rust

I am trying to pass a string by reference and manipulate the string in the function:

fn manipulate(s: &mut String) {                                                                                                                                                                                                          
  // do some string manipulation, like push
  s.push('3');  // error: type `&mut collections::string::String` 
                // does not implement any method in scope named `push`
}

fn main() {
  let mut s = "This is a testing string".to_string();
  manipulate(&s);          
  println!("{}", s);       
}

I have looked at examples on borrowing and mutibility. Also tried (*s).push('3'), but got

error: type `collections::string::String` does not implement any method in scope named `push`

I'm sure there's something obvious I'm missing or perhaps more reference material to read, but I'm not sure how to proceed. Thanks!

like image 611
EricC Avatar asked Aug 30 '26 08:08

EricC


1 Answers

Your code works with a slight modification on the newest version of rustc.

fn manipulate(s: &mut String) {                                                                                                                                                                                                          
  s.push('3');
}

fn main() {
  let mut s = "This is a testing string".to_string();
  manipulate(&mut s);          
  println!("{}", s);       
}
like image 141
IdolfHatler Avatar answered Sep 06 '26 01:09

IdolfHatler



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!