4 ms·
The first time I wanted a NLL, I did a hash lookup, matched on the option that came back, and wanted to insert into the hash in the None match arm. Since then
by surrealize 10y ago
The first time I wanted a NLL, I did a hash lookup, matched on the option that came back, and wanted to insert into the hash in the None match arm. Since then I think they've added convenience methods for getting or inserting. I still hope that IndexAddAssign (which would have addressed my use case) becomes an overloadable operator someday.
Recently I was parsing a line-oriented, whitespace delimited file and had to introduce a temporary ("line", below):
let f = File::open(path)?;
let reader = BufReader::new(f);
for line_result in reader.lines() {
let line = line_result?;
let mut word_iter = line.split_whitespace();
because I think something didn't live long enough when I did line_result?.split_whitespace(). I forget exactly what the code was like before I got it past the borrow checker, though.
For me, it seems like every time I dip a toe into rust I run into borrow/NLL issues right off the bat.
- steveklabnik 10y agoThank you! this is helpful. Ah, see, I'd go straight for Entry in the hash case. Which might be what you're referring to. yeah, that later one isn't NLL: it's that line_result?.split_whitespace() ^ ^ the ? will return your String, but then split_whitespace returns &strs to that String. Since it's not bound anywhere, the String would be deallocated at the end of the line, which would make the iterator dangling. NLL won't fix that.
- surrealize 10y agoThanks for following up. I found the hashmap example; it was from April 2013. I think that might have predated the Entry API. The code had ~ sigils! After failing to insert in the None arm, I tried rewriting it with find_or_insert and insert_or_update_with. Entry seems cleaner though. Thanks for the clarification about the second case not being solved by NLL. Those examples were the ones I had in my mental "code I would like the borrow checker to accept" bucket. Would Niko's proposals in that internals thread you linked ("Accepting nested method calls with an `&mut self` receiver") eliminate the need for the temporary in that second example?