rust - 如何获得对拥有对象的引用的生命周期? (无法为生命周期参数推断出合适的生命周期)

标签 rust

我如何编译它?

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/

相关文章:

testing - cargo test --release 导致堆栈溢出。为什么没有货台?

asynchronous - 使用异步 (tokio) rust-websocket 在客户端之间共享可变状态

rust - .next() 之后 for ... .zip() : Preventing iterator from being moved

tcp - 如何在 TcpStream 上设置连接超时

rust - 如何将 Rust 模块文档保存在单独的 Markdown 文件中?

opengl - 如何翻转OpenGL的三角形颜色?

rust - 多个 rust 文件需要使用相同的结构和函数

rust - 如何正确处理来自Rust中maxminddb::geoip2的AddressNotFound错误?

rust - 有什么方法可以创建 const &'static CStr 吗?

Rust 借用检查器仅在返回具有相同生命周期的引用的函数时多次提示借用是可变的