我如何编译它?
extern crate collections;
fn print_x_from_table(table: collections::BTreeMap<String, String>) {
let x: &str = table
.get(&String::from_str("x"))
.map(|s: &String| &s[]) // ERROR!
.unwrap_or("");
println!("table contains x={}", x);
}
它给出了这个错误:
src/rusttest.rs:5:22: 5:25 error: cannot infer an appropriate lifetime for lifetime parameter 'a in function call due to conflicting requirements
src/rusttest.rs:5 .map(|s: &String| &s[])
^~~
src/rusttest.rs:7:34: 7:35 note: first, the lifetime cannot outlive the expression at 7:33...
src/rusttest.rs:7 println!("table contains x={}", x);
^
note: in expansion of format_args!
<std macros>:2:43: 2:76 note: expansion site
<std macros>:1:1: 2:78 note: in expansion of println!
src/rusttest.rs:7:2: 7:37 note: expansion site
src/rusttest.rs:7:34: 7:35 note: ...so type `&str` of expression is valid during the expression
src/rusttest.rs:7 println!("table contains x={}", x);
如果 table
是一个引用参数,我知道我可以添加一个类型参数 'a
来指示 s
应该存在多长时间。但是当我拥有 table
时我该怎么做呢?
extern crate collections;
fn print_x_from_ref_table<'a>(table: &'a collections::BTreeMap<String, String>) {
let x: &'a str = table
.get(&String::from_str("x"))
.map(|s: &'a String| &s[])
.unwrap_or("");
println!("table contains x={}", x);
}
最佳答案
我设法通过避免使用闭包和使用匹配来让它工作。我认为这是可行的,因为在 .map(|s| &s[])
中,编译器会感到困惑,并认为引用的生命周期应该比实际生命周期短。
fn print_x_from_table(table: collections::BTreeMap<String, String>) {
let x = match table.get("x") {
Some(v) => &v[],
None => ""
};
println!("table contains x={}", x);
}
关于rust - 如何获得对拥有对象的引用的生命周期? (无法为生命周期参数推断出合适的生命周期),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28512314/