2014-10-01 97 views
1

我想通过引用传递一个字符串,并操纵该函数的字符串:按引用传递一个字符串,并操作字符串

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` 

我敢肯定有一些东西很明显我失踪或者更参考资料阅读,但我不知道如何着手。谢谢!

+0

更改'push_char' - >'push'必须是相对较新的,因为我不记得上次使用String功能的那部分时遇到了它。你使用什么版本(如果每天晚上,从什么日期开始)? – delnan 2014-10-01 22:05:18

+0

我使用的版本是'rustc 0.12.0-每晚(740905042 2014-09-29 23:52:21 +0000)' – EricC 2014-10-02 02:42:38

+0

纠正我以前的评论。我在一台不同的机器上试过相同的代码,这个机器上每晚都会出现0.12.0(740905042 2014-09-29 23:52:21 +0000)'。结果的错误实际上是更多的信息:'错误:不能借用'&'-pointer作为mutable'的不可改变的引用。基本上就像@IdolfHatler所描述的那样! – EricC 2014-10-02 02:49:16

回答

5

您的代码可以在最新版本的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);  
}