6

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!

3
  • The change push_char -> push must be relatively recent, since I don't recall encountering it the last time I used that part of String functionality. What version are you using (if nightly, from what date)? Commented Oct 1, 2014 at 22:05
  • The version I am using is rustc 0.12.0-nightly (740905042 2014-09-29 23:52:21 +0000) Commented Oct 2, 2014 at 2:42
  • To correct the previous comment I made. I tried the same code on a different machine, which has rustc 0.12.0-nightly (740905042 2014-09-29 23:52:21 +0000). The error that result is actually a lot more informative: error: cannot borrow immutable dereference of &-pointer as mutable. Basically it is exactly as @IdolfHatler described! Commented Oct 2, 2014 at 2:49

1 Answer 1

15

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);       
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.