The goal of this is to have an easily-scannable reference for the most common syntax idioms in JavaScript and Rust so that programmers most comfortable with JavaScript can quickly get through the syntax differences and feel like they could read and write basic Rust programs.
What do you think? Does this meet its goal? If not, why not?
JavaScript:
const foo = 1;
const bar = "hi";
let something_that_varies = 2;
something_that_varies += 1;
Rust:
let foo = 1i;
let bar = "hi";
let mut something_that_varies = 2;
something_that_varies += 1;
JavaScript:
// Function definition
function do_something(some_argument) {
return some_argument + 1;
}
// Function use
let results = do_something(3);
Rust:
// Function definition: takes an integer argument, returns an integer
fn do_something(some_argument: int) -> int {
some_argument + 1 // no semicolon in implicit return statements
}
// Function use
let results = do_something(3);
JavaScript:
if (x == 3) {
// ...
} else if (x == 0) {
// ...
} else {
// ...
}
Less commonly in JavaScript, it seems to me, is the switch
statement (not exactly equivalent since case
uses ===
):
switch (x) {
case 3:
// ...
break;
case 0:
// ...
break;
default:
// ...
break;
}
Rust:
if x == 3 {
// ...
} else if x == 0 {
// ...
} else {
// ...
}
More commonly used in Rust is pattern matching, which gives you other benefits:
match x {
3 => {
// ...
},
0 => {
// ...
},
_ => {
// ...
}
}
In JavaScript, this is usually done using output to the JavaScript console:
let x = 5;
console.log(`x has the value ${x}`);
Rust:
let x = 5;
println!("x has the value {}", x);
I'm not saying the word "array" on purpose :) Rust does have arrays, but they're fixed size, so you probably want a vector :)
JavaScript:
const i = ["a", "b", "c"];
i.push("d");
console.log(i[1]); // outputs b
Rust:
let i = vec!["a", "b", "c"]; // The vec! macro is provided to make initialization more convenient
i.push("d");
println!("{}", i[1]); // outputs b
JavaScript:
const i = ["a", "b", "c"];
for (let e of i) {
console.log(e);
});
Rust:
let i = vec!["a", "b", "c"];
for j in i.iter() {
println!("{}", j);
}