-
-
Save stevenblenkinsop/945de41353b05b7e53f0 to your computer and use it in GitHub Desktop.
This file contains 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
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(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Rust playpen:
http://is.gd/Uk0aYR