我无法理解以下功能有什么问题。
fn percuss<'a>(a: &'a mut str, b: &str, val: usize) -> &'a mut str {
a.to_string().insert_str(val, b)
}
Run Code Online (Sandbox Code Playgroud)
但是,我收到以下错误:
error[E0308]: mismatched types
--> src/lib.rs:2:5
|
2 | a.to_string().insert_str(val, b)
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `&mut str`, found `()`
Run Code Online (Sandbox Code Playgroud)
我没有或没有看到任何a.to_string().insert_str(val, b)退货的理由()。有人可以阐明我缺少注意/理解的内容吗?
pub fn insert_str(&mut self, idx: usize, string: &str)
Run Code Online (Sandbox Code Playgroud)
这意味着它返回()(Rust 中没有显式返回类型的函数返回())。事实上,它会改变传递给它的字符串,而不是创建一个新字符串。
你应该将其修复为
fn percuss<'a>(a: &'a mut str, b: &str, val: usize) -> &'a mut str {
let mut a = a.to_string();
a.insert_str(val, b);
&mut a
}
Run Code Online (Sandbox Code Playgroud)
现在会导致另一个错误:
error[E0515]: cannot return reference to local variable `a`
--> src/lib.rs:4:5
|
4 | &mut a
| ^^^^^^ returns a reference to data owned by the current function
Run Code Online (Sandbox Code Playgroud)
事实上,insert_str需要 aString而不是 a,&str因为它可能需要重新分配它。这意味着您需要返回一个拥有的值而不是引用:
fn percuss(a: &str, b: &str, val: usize) -> String {
let mut a = a.to_string();
a.insert_str(val, b);
a
}
Run Code Online (Sandbox Code Playgroud)
或者获取一个&mut String参数并就地修改它,而不返回任何内容:
fn percuss(a: &mut String, b: &str, val: usize) {
a.insert_str(val, b);
}
Run Code Online (Sandbox Code Playgroud)
也可以看看:
| 归档时间: |
|
| 查看次数: |
384 次 |
| 最近记录: |