【发布时间】:2014-09-26 09:23:34
【问题描述】:
我将一个字符串放入 Option 并尝试映射它,例如修剪字符串:
fn main() {
let s = " i want to be trimmed ".to_string();
let s_opt = Some(s);
let x = s_opt.map(|z| z.trim());
// let x = s_opt.map(|z| z.trim().to_string());
println!("'{:?}'", x);
}
编译器显示生命周期错误
error[E0597]: `z` does not live long enough
--> src/main.rs:5:27
|
5 | let x = s_opt.map(|z| z.trim());
| ^ - `z` dropped here while still borrowed
| |
| borrowed value does not live long enough
...
9 | }
| - borrowed value needs to live until here
这很清楚,因为z 只在闭包中定义,并且参数是按值传递的。
既然原始变量 s 存在于整个块中,编译器是否应该能够找出 z 实际上是 s?
我可以让它工作的唯一方法是添加to_string(参见注释行),然后我正在创建一个新的字符串对象。
我发现的另一个解决方案是将s_opt 设为Option<&String> 的类型(参见第二个代码块),但由于函数无法返回这种类型,因此这不是一个真正的选择。
fn main() {
let s = " i want to be trimmed ".to_string();
let s_opt = Some(&s);
let x = s_opt.map(|z| z.trim());
println!("'{:?}'", x);
}
如果map 的默认实现与此类似,我是否忽略了某些东西?
fn my_map<'r, F>(o: &'r Option<String>, f: F) -> Option<&'r str>
where
F: Fn(&'r String) -> &'r str,
{
match *o {
None => None,
Some(ref x) => Some(f(x)),
}
}
fn main() {
let s = " i want to be trimmed ".to_string();
let s_opt = Some(s);
let x = my_map(&s_opt, |x| x.trim());
println!("'{:?}'", x);
}
【问题讨论】:
标签: rust