我正试图了解借贷如何生锈。因此,在阅读了防锈书的一些主题之后。我陷入困境,试图了解为什么这段代码无法编译。
码fn main() {
let mut a = String::from("yes");
let b = function(&a);
a.clear();
println!("Hello {}", b);
}
fn function(a :&String) -> &str{
if a == "yes" {
"OK"
}
else{
"NO"
}
}
编译器给出此错误:
Compiling playground v0.0.1 (/playground)
error[E0502]: cannot borrow `a` as mutable because it is also borrowed as immutable
--> src/main.rs:4:5
|
3 | let b = function(&a);
| -- immutable borrow occurs here
4 | a.clear();
| ^^^^^^^^^ mutable borrow occurs here
5 | println!("Hello {}", b);
| - immutable borrow later used here
error: aborting due to previous error
For more information about this error, try `rustc --explain E0502`.
error: Could not compile `playground`.
To learn more, run the command again with --verbose.
但是我不明白为什么&a的范围不以函数范围结尾。
答案 0 :(得分:0)
您不精确定义index.html
函数的输出寿命。因此,借用检查器假定它与参数相同(请参见lifetime elision rules)。
您必须告诉借位检查器这些生存期不相同(在这种情况下,这意味着输出分片不依赖于输入分片)。在您的情况下,更确切地说是function
。
将函数声明更改为
static