Skip to content

Instantly share code, notes, and snippets.

@jakerr
Created November 8, 2014 11:16
Show Gist options
  • Save jakerr/cde925498ef7eaa7ec1b to your computer and use it in GitHub Desktop.
Save jakerr/cde925498ef7eaa7ec1b to your computer and use it in GitHub Desktop.
Made a simple mistake and wished rustc had warned me. Here's a reproduction.
use std::collections::hash_map::HashMap;
#[deriving(Show)]
struct Adder(uint);
impl Adder {
fn add(&mut self, i: uint) {
match self {
&Adder(ref mut a) => { *a += i; }
}
}
}
fn demonstrate_unused_adder_without_warning() {
let mut m: HashMap<uint, Adder> = HashMap::new();
m.insert(1, Adder(0));
m.insert(2, Adder(0));
{
let one = &mut m[1];
one.add(1);
}
{
// A simple mistake below. We accidently grab m[2] into a mut variable, rather than grab
// a mut reference to m[2].
let mut two = m[2];
two.add(1);
// Oops!
// We've just added to a copy of m[2] and then thrown it away without using it.
// It would be nice to have an unused_value warning here. #Could be better!
// Notice if I do the same thing with HashMap<uint, uint> we do get the unused_value warning.
}
println!("m[1]: {}\nm[2]: {} // Oops, and no warning!", m[1], m[2]);
}
fn demonstrate_unused_uint_with_warning() {
let mut m: HashMap<uint, uint> = HashMap::new();
m.insert(1, 0);
m.insert(2, 0);
{
let one = &mut m[1];
*one += 1;
}
{
// A simple mistake below. We accidently grab m[2] into a mut variable, rather than grab
// a mut reference to m[2].
let mut two = m[2];
two += 1;
// Oops!
// We've just added to a copy of m[2] and then thrown it away without using it.
// In this case because the copy is a simple type the warning makes it clear what went wrong. #GOOD!
// src/main.rs|47 col 11| 47:18 warning: variable `two` is assigned to, but never used, #[warn(unused_variables)] on by default
// src/main.rs:47 let mut two = m[2];
// ^~~~~~~
// src/main.rs|48 col 7| 48:10 warning: value assigned to `two` is never read, #[warn(unused_assignments)] on by default
// src/main.rs:48 two += 1;
// ^~~
}
println!("m[1]: {}\nm[2]: {} // Oops, but at least we were warned!", m[1], m[2]);
}
fn main() {
demonstrate_unused_adder_without_warning();
demonstrate_unused_uint_with_warning();
}
@jakerr
Copy link
Author

jakerr commented Nov 8, 2014

I made a simple mistake where I accidentally indexed via Index rather than IndexMut but since the thing I got back and mutated was not a simple type there was no warning.

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