通过引用传递字符串并操纵字符串

时间:2014-10-01 21:54:50

标签: rust

我试图通过引用传递一个字符串并操纵函数中的字符串:

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);       
}

我查看了borrowingmutibility上的示例。还试过(*s).push('3'),但得到了

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

我确信有一些显而易见的东西我缺失或者可能有更多参考资料要阅读,但我不知道该如何继续。谢谢!

1 个答案:

答案 0 :(得分:6)

您的代码稍微修改了最新版本的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);       
}