rust - 通过引用传递字符串并操作字符串

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

我看过关于 borrowing 的例子和 mutibility .还尝试了 (*s).push('3'),但得到了

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

我确定我缺少一些明显的东西或者可能有更多引用资料需要阅读,但我不确定如何继续。谢谢!

最佳答案

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

关于rust - 通过引用传递字符串并操作字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26151324/

相关文章:

rust - 为什么在 Rust 中使用不可变的 Vector 或 String

rust - 错误 : placement-in expression syntax is experimental and subject to change.(参见问题 #27779)

static - 为什么 Rust 中的 const 函数不能调用关联函数?

rust - Rust 中的 "item"是什么?

rust - 如何在捕获时向panick_info添加更多上下文?

rust - 导入其他依赖项需要的依赖项版本

rust - 如何在过程宏中指定条件代码

rust - 如何在跟踪中使用动态范围名称?

memory-management - Rust 分配内存布局与大小不一致

json - 使用rust serde反序列化不同的数据结构