错误[E0716]: 在借用时丢弃了临时值

4
我有一个函数,它接收一些参数,但当我尝试使用这些参数时,它会抛出一个错误。
// 这是函数:
pub fn solc_compile(compiler: &str, file: &str, out: &str, config: templates::Config) {
    let mut args = vec![
        "--bin",
        "--abi",
        "--include-path",
        "./libs",
        "--include-path",
        "./node_modules",
        "--output-dir",
        out,
    ];

    if config.compiler.optimize {
        let runs: &str = config.compiler.runs.to_string().as_str();
        args.push("--optimize");
        args.push("--optimize-runs");
        args.push(runs);
    }
}

// 在函数参数中使用的配置类型(config templates::Config)。

templates.rs

// config templates.
#[derive(Deserialize, Serialize)]
pub struct Config {
    pub info: ConfigInfo,
    pub compiler: ConfigCompiler,
}

// config.info templates.
#[derive(Deserialize, Serialize)]
pub struct ConfigInfo {
    pub name: String,
    pub license: String,
}

// config.compiler templates.
#[derive(Deserialize, Serialize)]
pub struct ConfigCompiler {
    pub solc: String,
    pub optimize: bool,
    pub runs: i64,
}

这是当我运行cargo build时遇到的错误。

error[E0716]: temporary value dropped while borrowed
  --> src/solc.rs:58:26
   |
58 |         let runs: &str = config.compiler.runs.to_string().as_str();
   |                          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^         - temporary value is freed at the end of this statement
   |                          |
   |                          creates a temporary which is freed while still in use
...
61 |         args.push(runs);
   |                   ---- borrow later used here
   |
   = note: consider using a `let` binding to create a longer lived value

1
这个回答解决了你的问题吗?为什么编译器告诉我要考虑使用"let"绑定,而我已经在使用了?(https://dev59.com/PYjca4cB1Zd3GeqPxX1n) - E net4
config.compiler.runs.to_string()获取的值未分配给变量,因此它会过早地被丢弃。请参见:https://dev59.com/Dl4b5IYBdhLWcg3w-14I https://dev59.com/K5ffa4cB1Zd3GeqP3R4s https://dev59.com/CFYN5IYBdhLWcg3wR2k- - E net4
我在stackoverflow上问了一个简明的问题,关于Rust常见错误error[E0716]error E0716: temporary value dropped while borrowed (rust),它链接回到这个问题。 - JamesThomasMoon
1个回答

6
你使用to_string创建了一个新的String,但没有给它一个变量来存储,所以它会在下一个;之后被删除。你可以通过不立即调用as_ref来解决这个问题:
if config.compiler.optimize {
    let runs: String = config.compiler.runs.to_string();
    // ..
    args.push(runs.as_ref());
}

但现在你面临下一个问题:你的 args 向量包含字符串引用,但是 runs 中的字符串会在 if 块结束时失效。它必须至少存活与 args 一样长时间。您可以通过将 args 的声明和赋值分开来解决此问题:

let runs: String;
if config.compiler.optimize {
    runs = config.compiler.runs.to_string();
    // ...
    args.push(runs.as_str());
}

另一种可能性是将args设为Vec<String>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接