我有一个接收一些参数的函数,但是当我尝试使用该参数时,它会抛出错误。
// 功能
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);
}
}
Run Code Online (Sandbox Code Playgroud)
// 在函数参数上使用的配置类型(config templates::Config)。
模板.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,
}
Run Code Online (Sandbox Code Playgroud)
这是我在运行 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
Run Code Online (Sandbox Code Playgroud)
您创建了一个新String的to_string,但没有给它一个变量来生存,所以它会在下一个 中消亡;。您可以通过不as_ref立即致电来解决该问题:
if config.compiler.optimize {
let runs: String = config.compiler.runs.to_string();
// ..
args.push(runs.as_ref());
}
Run Code Online (Sandbox Code Playgroud)
但现在你遇到了下一个问题:你的args向量包含字符串引用,但字符串 inruns在块的末尾消失if。它的寿命必须至少为args。您可以通过拆分声明和赋值来解决此问题args:
if config.compiler.optimize {
let runs: String = config.compiler.runs.to_string();
// ..
args.push(runs.as_ref());
}
Run Code Online (Sandbox Code Playgroud)
另一种可能性是制作args一个Vec<String>.
| 归档时间: |
|
| 查看次数: |
3158 次 |
| 最近记录: |