【发布时间】:2020-01-05 17:16:33
【问题描述】:
看看这个函数:
fn exec(cli: Vec<&str>) {
eprintln!("execing: {:?}", cli);
let args: Vec<&CStr> = cli.iter()
.map(|s| CString::new(s.as_bytes()).unwrap().as_c_str())
.collect();
execv(args[0], &args);
debug(args);
}
它接受Vec<&str> 并将其作为命令执行。我无法将其转换为Vec<&CStr>(这是execv 需要的)。编译器针对map 操作报告此错误:
error[E0515]: cannot return value referencing temporary value
--> src/idea.rs:141:18
|
141 | .map(|s| CString::new(s.as_bytes()).unwrap().as_c_str())
| -----------------------------------^^^^^^^^^^^
| |
| returns a value referencing data owned by the current function
| temporary value created here
如何解决这个错误?
【问题讨论】:
-
您的 map 闭包不能返回对您在闭包中创建的 CString 的字符串引用,因为一旦您从闭包返回,它将无效。只需将 args 设为 CString 的 Vec 即可。从那里你将有更多的类型不匹配需要处理,但一步一步
标签: rust lifetime borrow-checker borrow