loading...

A JavaScript Developer's Cheatsheet for Rust

tindleaj profile image Austin Tindle Originally published at tndl.me on ・4 min read

Learning a new programming language is a great opportunity to learn new universal concepts and patterns that apply to all languages, not just the one you're learning. However, before you can get a handle on all the new stuff a language provides, first you have to figure out how to write the new language like you would write whatever old language(s) you know.

For the JavaScript developer, Rust offers a plethora of new and sometimes brain-bending concepts that exist in Rust but not in JavaScript. But in order to appreciate those concepts, first you have to get a handle on the basic syntax of the language. To speed up that process, you can use the JavaScript you already know to draw parallels to the Rust equivalents.

This cheatsheet provides some basic comparisons between JavaScript syntax and the parallels in Rust. It purposefully sticks to the basics that have decent parallels, to get you comfortable writing some simple programs in Rust.

Don't let the label of "Systems Programming Language" discourage you. Rust is an incredibly accessible language, in more ways than one. Use what you already know and learn some Rust!

Variables (bindings)

Rust variables are immutable by default. This is sort of like having all varaibles be const in JavaScript. JavaScript const is shallow, but Rust variables cannot be mutated at all unless you declare that variable mut.

// JavaScriptlet value = 10;let greeting = "Hello!";let counter = 0;counter += 1;

// Rustlet value = 10; // Cannot be changedlet greeting = "Hello!"; // Also immutablelet mut counter = 0; // This can be changedcounter += 1;

Printing Output

Rust's println! takes a string argument, which sort of acts like a JavaScript template string.

// JavaScriptlet name = "Austin Tindle";console.log(`Hello ${name}!`);

// Rustlet name = "Austin Tindle";println!("Hello {}!", name);

Functions

The main function in Rust is the entrypoint to the program, and other functions need to be called from main. In JavaScript there is no special entrypoint function.

// JavaScriptfunction weather() { console.log("Sunny!");}weather();

// Rustfn weather() { println!("Sunny!");}fn main() { weather();}

Conditionals

If/Else

// JavaScriptif (true === false) { console.log("Never happens.");} else if (false === true) { console.log("Also never happens.");} else { console.log("Perfection.");}

// Rustif true == false { println!("Impossible!");} else if false == true { println!("Still impossible!");} else { println!("This works.");}

Unlike in JavaScript, Rust does not have "truthy" values. It's strict static typing means that conditional expressions need to evaluate to a bool.

// Rustlet not\_a\_boolean = "I'm a String";if not\_a\_boolean { // Error: mismatched types expected `bool`, found `&str`}

Switch & Match

Switch statements aren't as widely used in JavaScript as if/else, but match statements in Rust are very popular. They aren't exactly the same, and match statements have a lot of powerful uses not available to JavaScript switch statements.

// JavaScriptlet stone = "Thunder Stone";switch (stone) { case "Thunder Stone": console.log("Jolteon!"); break; case "Water Stone": console.log("Vaporeon!"); break; case "Fire Stone": console.log("Flareon!"); break; default: console.log("Eevee!");}

// Rustlet stone = "Thunder Stone";match stone { "Thunder Stone" => println!("Jolteon!"), "Water Stone" => println!("Vaporeon!"), "Fire Stone" => println!("Flareon!"), \_ => println!("Eevee!")}

Importing Other Code Using Modules

In Rust, any function marked pub can be imported into another file. Any file that is not main.rs or lib.rs automatically gets a namespace based on its source file name. The mod keyword pulls in source files with equivalent filenames.

The use keyword brings nested items into the current scope, sort of like the import {x} from 'y' syntax in JavaScript.

// JavaScript// houston.jsexport default function launch() { console.log("Liftoff!");}export function abort() { console.log("Aborting!");}

// JavaScript// main.jsimport launch, { abort } from "./houston";launch();abort();

// Rust// houston.rspub fn launch() { println!("Liftoff!");}pub fn abort() { println!("Aborting!");}

// Rust// main.rsmod houston;use houston::{ launch };fn main() { launch(); houston::abort();}

Arrays & Vectors

Rust has a data type called 'array', but it's not the type of array we're used to in JavaScript. A growable list is called a Vector in Rust, and is available via

// JavaScriptlet languages = ["JavaScript", "TypeScript", "Rust", "HTML"];languages.pop();console.log(languages[0]);

// Rust// A shorthand macro syntaxlet mut languages = vec!["JavaScript", "TypeScript"];languages.push("Rust");// Full syntaxlet mut alphabets = Vec::new();alphabets.push("Greek");alphabets.push("Roman");println!("{} {}", languages[2], alphabets[0]);

Iterating

// JavaScriptlet utensils = ["Fork", "Spoon", "Spork", "Knife"];for (let utensil of utensils) { console.log(`Eating with a ${utensil}.`);}

// Rustlet utensils = vec!["Fork", "Spoon", "Spork", "Knife"];for utensil in utensils.iter() { println!("Eating with a {}.", utensil);}

Other Resources

Are you a JavaScript developer trying to learn Rust? Send me an email at tindleaj@gmail.com. I'm working on stuff you'll be interested in.

Discussion

pic
Editor guide