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.
writer1
lives in the scope of the loop.vecs
lives outside.writer1
is dropped at the end of the loop, butvecs
probably is used later. But its contentsdoing_this
depend (reference) on the dropped contents ofwriter1
. Ifdoing_this
were aVec<String>
(owned) there would be no problem. – CoronA.map(String::from)
, which will do same thing without additional closure noise. You cannot use clone here, because you're providing&str
's. Not that it's a bad thing,&String
is often code smell, because you provide unnecessary indirection for little to no gain. Also, the methods you use deliberately provide&str
, as you don't always want to copy data, which is both more performant and doesn't allocate more memory unless you yourself declare withString::from
/str::to_owned
. – SahsahaeString
andstr
? – trentcl