Skip to content

Instantly share code, notes, and snippets.

@graue
Created January 3, 2013 08:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save graue/4441792 to your computer and use it in GitHub Desktop.
Save graue/4441792 to your computer and use it in GitHub Desktop.
Find first even number in a list (generic version)
extern mod std;
use num::Num;
// Based on some example code by Armin Ronacher
fn find_even<T:Copy Num cmp::Eq>(vec: &[T]) -> Option<T> {
let zero: T = Num::from_int(0);
let two: T = Num::from_int(2);
for vec.each |x| {
if *x % two == zero {
return Some(*x);
}
}
None
}
fn main() {
io::println(match find_even(@[1,2,3,5,7,9,10]) {
Some(x) => int::str(x),
None => ~"No even numbers"
});
}
@graue
Copy link
Author

graue commented Jan 3, 2013

In other words you just have to check every pointer, always?

But what if you check the pointer against nil on line 37, and then assume it's non-nil and dereference it on line 52, and a later pull request accidentally deletes the check on line 37? Now your assumption is wrong and stuff blows up.

In Rust it is, as I understand it, impossible to have a pointer that will blow up if dereferenced. If you have a &T you know that it isn't nil/null/undefined, the check (if necessary) has already been done. That's encoded in the type system. It's a big safety feature.

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