小编Api*_*nix的帖子

将 mut 引用传递给函数,然后将其返回

我尝试从一个小时开始编写代码示例,在String. 因此,主函数借用了一个字符串给一个添加空格的函数,然后,我想将字符串返回到主函数中。

fn main() {
    ...
    let mut line = String::new();
    line = make_spaces(5, &mut line);
}

fn make_spaces(number: u8, string: &mut String) -> &mut String {
    for _ in 0..number {
        string.push(' ');
    }
    string
}
Run Code Online (Sandbox Code Playgroud)

但借用检查器给我以下错误:

error[E0308]: mismatched types
  --> src/main.rs:14:12
   |
14 |     line = make_spaces(left_spaces, &mut line);
   |            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   |            |
   |            expected struct `String`, found `&mut String`
   |            help: try using a conversion method: `make_spaces(left_spaces, &mut line).to_string()`

Run Code Online (Sandbox Code Playgroud)

我是新手rust,我知道我不懂借钱。但我上网查了一下,还是不太明白。

据我了解,我将line所有权赋予 …

ownership rust borrow-checker

2
推荐指数
1
解决办法
3709
查看次数

标签 统计

borrow-checker ×1

ownership ×1

rust ×1