gpt4 book ai didi

rust - 函数在借用 String 后返回字符串文字时出错

转载 作者:行者123 更新时间:2023-11-29 08:17:42 25 4
gpt4 key购买 nike

<分区>

我正在尝试了解借用在 Rust 中是如何工作的。所以在阅读了 rust 书的一些主题之后。我卡住了,试图理解为什么这段代码无法编译。

代码
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 的作用域不以函数作用域结尾。

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com