Skip to content

Instantly share code, notes, and snippets.

@jgarvin
Created August 23, 2020 21:19
Show Gist options
  • Save jgarvin/e48de9cd9d354692b9b2cef180d42ffc to your computer and use it in GitHub Desktop.
Save jgarvin/e48de9cd9d354692b9b2cef180d42ffc to your computer and use it in GitHub Desktop.
#![allow(dead_code)]
struct A {
data: i32,
}
struct B {
data: i32,
}
struct Composite {
a: A,
b: B,
}
fn take_individually(a: &mut A, b: &mut B) {
a.data = 3;
b.data = 3;
}
fn create() {
let mut c = Composite {
a: A { data: 0 },
b: B { data: 0 },
};
// rustc smart enough to recognize these are disjoint object trees!
take_individually(&mut c.a, &mut c.b);
}
fn passed_in(c: &mut Composite) {
// rustc smart enough to recognize these are disjoint object trees!
take_individually(&mut c.a, &mut c.b);
}
struct X {
data: i32,
}
struct Nested {
x: X,
}
fn take_individually2(n: &mut Nested, x: &mut X) {
n.x.data = 3;
assert!(x.data == 3);
}
fn create_nested() {
let mut n = Nested { x: X { data: 0 } };
// rustc detects these are not disjoint object trees and won't let you borrow twice!
// take_individually2(&mut n, &mut n.x)
}
fn main() {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment