Skip to content

Instantly share code, notes, and snippets.

@stevenblenkinsop
Forked from jakerr/index_mut_warnings.rs
Last active August 29, 2015 14:08
Show Gist options
  • Save stevenblenkinsop/945de41353b05b7e53f0 to your computer and use it in GitHub Desktop.
Save stevenblenkinsop/945de41353b05b7e53f0 to your computer and use it in GitHub Desktop.
use std::collections::hash_map::HashMap;
use std::cell::Cell;
#[deriving(Show)]
struct Adder<'a>(&'a Cell<uint>);
impl <'a> Adder<'a> {
fn add(&mut self, i: uint) {
let &Adder(cell) = self;
cell.set(cell.get() + i);
}
}
fn demonstrate_unused_adder_without_warning() {
let m1 = &Cell::new(0);
let m2 = &Cell::new(0);
let mut m: HashMap<uint, Adder> = HashMap::new();
m.insert(1, Adder(m1));
m.insert(2, Adder(m2));
{
let one = &mut m[1];
one.add(1);
}
{
// A simple mistake below? Or maybe not...
let mut two = m[2];
two.add(1);
// Have we just added to a copy of m[2] and then thrown it away without using it?
// Let's see...
}
println!("m[1]: {}\nm[2]: {} // Aha, it worked! Interior mutability to the rescue!", m[1], m[2]);
}
fn main() {
demonstrate_unused_adder_without_warning();
}
@stevenblenkinsop
Copy link
Author

Rust playpen:
http://is.gd/Uk0aYR

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment