Skip to content

Instantly share code, notes, and snippets.

@rybla
Created August 6, 2024 16:56
Show Gist options
  • Save rybla/7776eff2b10043f16765627e52498359 to your computer and use it in GitHub Desktop.
Save rybla/7776eff2b10043f16765627e52498359 to your computer and use it in GitHub Desktop.
// while iterating, have a `mut bindings: Vec<Bindings>`
// have a structure of Scopes that contain references to values in `bindings`
// a Binding doesn't refer to a Scope
// at the end, return `bindings`, so Scopes cannot own anything in bindings
// mutable reference is a subtype of immutable reference
fn example<'source>(
bindings: &mut Vec<Box<Binding<'source>>>,
names: Vec<&'source str>,
) {
let mut scope: Scope<'source> = Scope { bindings: vec![] };
for name in names.into_iter() {
let binding: Binding<'source> = Binding { name };
// borrowed mutably
bindings.push(Box::new(binding));
// so, can't borrow immutably here
let binding_ref: Box<Binding<'source>> = bindings.last().unwrap().clone();
scope.bindings.push(binding_ref);
}
}
#[derive(Debug, Clone)]
struct Binding<'source> {
name: &'source str,
}
#[derive(Debug, Clone)]
struct Scope<'source> {
pub bindings: Vec<Box<Binding<'source>>>,
}
fn main() {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment