Rust E0597 - borrowed value does not live long enough

戏子无情 提交于 2020-06-01 06:07:30

问题


Alright so, I'm about a month in on Rust and doing more mundane tasks in it just for exercise. I came across the calamine crate to read in data from excel. I thought I was well on my way to understand burrowing and ownership, but this one is new and even reading some other examples and looking in the docs didn't help explain it or I at least haven't came across it. So a basic for loop

 for row in r.rows() {
        let writer1 = row[11].to_string(); 
        if let Some(cap) = exp.captures(&writer1) { // borrow here
            println!("{} --- {}", &cap[1], &cap[2]);
        } else {
            println!("{}", &writer1); // and borrow here
        }
        // This works fine... great
        // writer1 is type String
        // row     is type &[calamine::datatype::DataType]

        let doing_this: Vec<&str> = writer1.split_whitespace().collect();

        vecs.push(doing_this); // assume vecs exists above for
    }

When I go to push the collection "doing_this" into a vector it gives the E0597 error. Can anyone help explain what is going on? I assume lifetimes but I already created a string from the column and took ownership.


回答1:


        // changed this 
        let doing_this: Vec<&str> = writer1.split_whitespace().collect();


        // to this
        let doing_this: Vec<String> =
            writer1.split_whitespace().map(|x| x.to_owned()).collect();

        // or as suggested to clean up the closure
        let doing_this: Vec<String> =
            writer1.split_whitespace().map(String::from).collect();


来源:https://stackoverflow.com/questions/59004640/rust-e0597-borrowed-value-does-not-live-long-enough

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!