Skip to content

Instantly share code, notes, and snippets.

@agrif
Created July 14, 2020 12:21
Show Gist options
  • Select an option

  • Save agrif/1a754ba7930b5bb87bcf864e0dd34506 to your computer and use it in GitHub Desktop.

Select an option

Save agrif/1a754ba7930b5bb87bcf864e0dd34506 to your computer and use it in GitHub Desktop.
zero_ref_mut!(FOO, u32);
fn main() {
let mut val: u32 = 2;
// initialize static FOO
// fzero acts like a MutexHandle
// while it's in scope, FOO is used to store &mut val
let mut fzero = FOO.claim(&mut val).unwrap();
// but...
assert_eq!(std::mem::size_of_val(&fzero), 0);
// fzero.borrow() acts like &val, but...
let fref = fzero.borrow();
assert_eq!(std::mem::size_of_val(&fref), 0);
assert_eq!(*fref, 2);
// fzero.borrow_mut() acts like &mut val, but...
let mut fmut = fzero.borrow_mut();
assert_eq!(std::mem::size_of_val(&fmut), 0);
*fmut += 2;
assert_eq!(*fmut, 4);
// when all is said and done, these changes are reflected in val
std::mem::drop(fzero);
assert_eq!(val, 4);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment