【问题标题】:Why Is Temporary Value Dropped While Borrowed An Issue? [duplicate]为什么借用时临时价值下降是一个问题? [复制]
【发布时间】:2021-05-05 19:22:52
【问题描述】:

为什么这是一个问题?什么是所有权问题?

fn test_code() -> String {
    let mut mod_string = "";

    let y = ["", "", " "];

    for x in &y {
        if x.to_string() == " " {
            // getting temp value dropped below... why?
            mod_string = &(mod_string.to_owned() + &x.to_string() + ",");
        }
    }

    mod_string.to_string()
}
error[E0716]: temporary value dropped while borrowed
  --> src/lib.rs:9:27
   |
9  |             mod_string = &(mod_string.to_owned() + &x.to_string() + ",");
   |                           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^- temporary value is freed at the end of this statement
   |                           |
   |                           creates a temporary which is freed while still in use
...
13 |     mod_string.to_string()
   |     ---------- borrow later used here
   |
   = note: consider using a `let` binding to create a longer lived value

【问题讨论】:

标签: rust


【解决方案1】:

您正在尝试维护一个&str,但这是行不通的,因为&str 是一个字符串slice,因此必须指向现有数据。您希望变量拥有数据,因此请改用String

fn test_code() -> String {
    // convert to String here
    let mut mod_string = "".to_owned();

    let y = ["", "", " "];

    for x in &y {
        if x.to_string() == " " {
            mod_string = mod_string + x + ",";
        }
    }

    // no longer need to convert to String here
    mod_string
}

【讨论】:

    猜你喜欢
    • 2021-03-05
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-05
    • 2022-01-05
    • 2018-05-19
    相关资源
    最近更新 更多