Created
January 3, 2013 08:19
-
-
Save graue/4441792 to your computer and use it in GitHub Desktop.
Find first even number in a list (generic version)
This file contains hidden or 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
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" | |
}); | |
} |
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
I don't see a significant difference.
In Rust, when... [y]ou see the
Option<...>
in the function's type signature and you know you have to explicitly use theSome
andNone
constructors.In Go, when you see a
*T
in the function's type signature, you know you have to explicitly check fornil
being returned.If you don't, yes, deferencing a null pointer will blow things up. What happens in Rust?