Skip to content

Instantly share code, notes, and snippets.

@graue
Last active December 10, 2015 13:19
Show Gist options
  • Save graue/4440531 to your computer and use it in GitHub Desktop.
Save graue/4440531 to your computer and use it in GitHub Desktop.
Map example in Rust
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"
*/
@elimisteve
Copy link

package main

func main() {
    powers := func(nums []int) (squares []int) {
        for _, x := range nums {
            squares = append(squares, x*x)
        }
        return
    }([]int{1,2,3,4})

    for _, num := range powers {
        println(num)
    }
}

Let me know when it's concurrency time.

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