Hello, Rust!
Introduction
Welcome to Rust for JavaScript Developers! It's fantastic to have you here. Let's dive right in.
Installation
Let's install Rust. If you're on macOS, Linux, or another Unix-like OS, spin up a terminal and enter the following:
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
This will use rustup to install the latest stable version of Rust.
rustup is a tool to install the entire Rust toolchain (including Cargo which we'll talk about later) and lets you switch channels (to nightly versions of Rust for instance if you like living dangerously)
Once rustup
is done doing its thing, run rustc --version
to ensure you got everything you need and to see the version of Rust you just installed. rustc
is the Rust compiler by the way.
Now, let's write our very first Rust program! Are you ready? Create a file, call it hello-rust.rs
and open it in your favourite editor.
Type the following into your brand new hello-rust.rs
file.
fn main() {
println!("Hello, Rust!");
}
Now, time to compile it. Go back to the terminal and run:
rustc hello-rust.rs
Lo and behold, you'll now have a nice little compiled binary in the same directory called hello-rust
which you can run by running:
./hello-rust
This should print out "Hello, Rust!" in your terminal. You did it!
Give yourself a pat on the back. You just wrote your first Rust program!
Now let's take a deeper look into that syntax.
Syntax
Functions
To create a function in Rust, you use the fn
keyword. This is just like the function
keyword in JavaScript. The rest is identical syntactically.
fn hola() {}
Printing
println!
as the name suggests is how you print something (with a nice line in the end) to the screen. Much like our dear friend, console.log
. One quick difference though. println!
is not a function. It's a macro. We'll learn what those are later but that explains the exclamation mark. Macros are called just like functions but with the additional !
before the parenthesis.
String literals
String literals in Rust (just like JavaScript) live in double quotes. Unlike JavaScript though, you can't use ", "
or `
interchangeably so you need to stick with a pair of "
.
Semicolons
The final bit of relevant syntax in our Hello, Rust example is that little semicolon. Unlike JavaScript, semicolons in Rust are not optional. Every statement in Rust must end with a semicolon.
Semantics
main
Semantically, the only bit in our example we must talk about is the main
function. Every Rust program needs to have a main
function. That is the entry point to your program and is called when your binary is executed. If this were JavaScript, we would have to call it ourselves.
That was a fun little dip, wasn't it? Go grab a tasty beverage of your choice and let's get into statements and variables next.