Created
December 11, 2021 13:35
-
-
Save qguv/53f27e7d0947232ff898831cdfa88250 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// extended from example at: | |
// https://willmurphyscode.net/2018/04/25/fixing-a-simple-lifetime-error-in-rust/ | |
pub struct SomeCollection<'a> { | |
strings: Vec<&'a str>, | |
} | |
impl<'a> SomeCollection<'a> { | |
pub fn new() -> Self { | |
SomeCollection { | |
strings: Vec::new(), | |
} | |
} | |
pub fn insert(&mut self, s: &'a str) { | |
self.strings.push(s); | |
} | |
// an attempt to avoid the borrow error, see below | |
pub fn insert_push(&mut self, v: &'a mut Vec<String>, value: String) { | |
// store in vector | |
v.push(value); | |
// get reference to just-stored item | |
let vp = v.last().unwrap(); | |
// store reference in collection | |
self.insert(vp); | |
} | |
// another attempt at avoiding the borrow error, see below | |
pub fn insert_last(&mut self, v: &'a Vec<String>) { | |
self.strings.push(v.last().unwrap()); | |
} | |
} | |
#[cfg(test)] | |
mod tests { | |
use super::SomeCollection; | |
#[test] | |
fn test() { | |
let mut storage = Vec::new(); | |
let mut my_collection = SomeCollection::new(); | |
(0..10).for_each(|item| { | |
let value = format!("value number {}", item + 1); | |
// error: borrow of moved value (rust doesn't update the reference, sure, understandable) | |
//storage.push(value); | |
//my_collection.insert(&value); | |
// error: borrowed data escapes outside of closure | |
storage.push(value); | |
my_collection.insert(storage.last().unwrap()); | |
// error: borrowed data escapes outside of closure | |
//storage.push(value); | |
//my_collection.insert_last(&storage); | |
// error: borrowed data escapes outside of closure | |
//my_collection.insert_push(&mut storage, value); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment