Last active
December 10, 2015 13:19
-
-
Save graue/4440531 to your computer and use it in GitHub Desktop.
Map example in Rust
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; | |
fn main() { | |
let powers = [1, 2, 3, 4].map(|x| *x * *x); | |
for powers.each |num| { | |
io::println(int::str(*num)); | |
} | |
} | |
/* | |
Working version of this example: | |
let powers = [1, 2, 3, 4].map(|x| x ** 2); | |
from http://lucumr.pocoo.org/2012/10/18/such-a-little-thing/ | |
The problems with that code are: | |
1. There's no ** operator in Rust. Like C, you have to call a function | |
for exponentiation. For squaring, you can of course do "x * x" | |
2. map() passes a reference to the array object, not the object itself. | |
So type of x is &int, not int, and we must dereference it, | |
returning "(*x) * (*x)" or "*x * *x" | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Let me know when it's concurrency time.