Rust 函数在借用字符串后返回字符串文字时出错

Rust 函数在借用字符串后返回字符串文字时出错,rust,Rust,我在试着理解借钱在铁锈中是如何运作的。所以在读了铁锈书的一些主题之后。我陷入困境,试图理解为什么这段代码不能编译 代码 编译器出现以下错误: 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 = functi

我在试着理解借钱在铁锈中是如何运作的。所以在读了铁锈书的一些主题之后。我陷入困境,试图理解为什么这段代码不能编译

代码 编译器出现以下错误:
   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的作用域不以函数作用域结束。

您没有精确计算
函数的输出寿命。因此,借用检查器假定它与参数相同(请参见)

您必须告诉借阅检查器,这些生存期是不同的(这意味着在这种情况下,输出切片不依赖于输入切片)。更准确地说,在您的情况下,它是静态的

将函数声明更改为

fn函数(a:&String)->&'static str{
   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.