paint-brush
An Intro to Rust for JavaScript Developersby@michaelsalim
3,343 reads
3,343 reads

An Intro to Rust for JavaScript Developers

by Michael SalimMay 9th, 2022
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Rust has quite a vast documentation, so if you’re looking for details, please google them instead. Rust is a typed language, so it’s closer to TypeScript. You’ll have a much better experience if you already know TS. You can think of it like a custom syntactic sugar that writes other code. Both syntaxes are similar (**variable_name: Type**) horray! The closest thing we have to this is the closest thing to this are the link between a link.

Company Mentioned

Mention Thumbnail
featured image - An Intro to Rust for JavaScript Developers
Michael Salim HackerNoon profile picture


This article lists several topics that will help you understand Rust quickly if you are a JavaScript developer. Many tutorials start from scratch. But if you already know something else, why not compare them?


These are differences that I wished I could refer to before starting Rust, kept short.


Disclaimer!

I’m very far from being well versed in Rust. These are how I interpret them and no more than that. Rust has quite a vast documentation, so if you’re looking for details, please google them instead. The book is a great starting point for learning rust. My goal is to list the important things so that you (and me in the future) can skip common programming concepts and focus on the differences based on the knowledge you already know.

Types

Rust is a typed language, so it’s closer to TypeScript. You’ll have a much better experience if you already know TS.


For the most part, both syntaxes are similar (variable_name: Type) horray!

snake_case

Yep, no getting around it.

What’s this symbol?

1. Question mark (?)

You may see ? after a function call like so: my_function()?;.

No, it’s not optional chaining. It’s an error handling magic for functions that can fail (fallible functions). You'll commonly see this when dealing with asynchronous functions. More about this later.

Documentation

2. Exclamation mark on functions (!)

Example: println!("{:?}", my_variable);

This indicates that it’s a macro. JS doesn't have anything similar to this. Macros are a way of writing code that writes other code. You can think of it like a custom syntactic sugar. Just use it if the function example shows it.

3. The & symbol

Example: &your_variable

To get the reference. You’ll know this if you used low-level languages like C. More later.

Syntax

  1. Semicolon (;) at the end of each line is mandatory

  2. Exception: Semicolon (;) is not mandatory on the last line of a function. In this case, it’s a shortcut for returning that line.

  3. Function syntax is slightly different. Not a big deal.

    fn foo(num: i32) -> i32 {
      3 // See no.2
      // or
      // return 3;
    }
    


  4. Decorator syntax also different. It’s also called Attributes.

What are these keywords?

struct

It’s a JSON object. (Ok, it’s more complicated but see the docs for that)

type Person = {
    firstName: string;
    lastName: string;
};


struct Person {
    first_name: String,
    last_name: String,
}

trait

An interface

impl

An implementation of trait. The closest thing we have to this are classes. It's the link between a trait and a type. I’ve not used it

enum

Quite similar to Typescript enums in a way. But you can store data in it. It’s pretty neat and quite an important concept to understand for async.

Console.log

Not as easy, unfortunately. It’s more similar to printf from other languages

println!("{:?}", my_variable);

Library/Dependencies

Use Cargo.toml instead of package.json. You’ll want to add them manually (instead of using a command like yarn add)

Documentation

Example:

[dependencies]
chrono = "0.4"
egg-mode = "0.16.0"

Importing

Rust has modules. It’s quite different from JS but basically:

They’re sort of like namespaces.


Here’s a breakdown on importing a dependency:

use rocket::serde::{json::Json, Deserialize, Serialize};

use - use this instead of import

rocket - this is the package name

:: - accessing a module

serde - the module name

{json::Json, Deserialize, Serialize} - things to actually import


Some more syntax:

use chrono::prelude::*;

use rusqlite::Result;

Importing from local files

Best explanation: https://doc.rust-lang.org/rust-by-example/mod/split.html


Use mod to the path/file you want to import to make the compiler include the module.


Then use to import it. Note: mod automatically imports it too. In this case, you will need to prefix it with crate.


Example:

use crate::your_file_or_module;

Note: mod.rs is a special filename which acts like index.js


See the link above for examples.

Const vs let

In JavaScript, you’d use const most of the time because it’s immutable.


In Rust, you’ll want to use let instead. This is immutable by default. If you want it to be mutable, use mut keyword. const is reserved for actual constants (so you can’t calculate the value from another variable)

let immutable_variable = ...;
let mut mutable_variable = ...;
const MY_CONSTANT = "CONSTANT";

Library Documentation

If the Github repo doesn’t link to the documentation page, you can probably get to it like this:

Asynchronous

By far, the 2 most confusing topics are futures and ownership. I would recommend reading more comprehensive documentation for these. Let’s talk about futures first.


Future is like a Promise. Unlike JS, Rust has a type for the result of the promise/future called Result. It also accepts the error type on the generics (I wish JS has this). You can also use Result on its own without future.

Executing (or “consuming”) Future

The standard library is quite bare-bones so you’ll need to import something else (Think bluebird for JS). You need an executor to run a future. I recommend using https://github.com/tokio-rs/tokio and reading their documentation.

.await to await a function

async_function().await; Interesting syntax, yeah? Actually quite nice since you don’t have to wrap it with brackets like in JS.

Handling Result

This is another important one. Rust is safe so you’ll need to handle everything. Yes, all error cases unlike JS!


The Result enum has Ok and Err. If the future is successful, it returns Ok, otherwise Err.


The most comprehensive way to handle both cases:

let f = File::open("hello.txt");

let mut f = match f {
    Ok(file) => file,
    Err(e) => return Err(e),
};

The above uses the pattern matching syntax which is also great.


This is quite verbose so there are 2 common ways to shorten it:


  1. Using .unwrap()

Example: let my_value = async_function().await.unwrap();

This gets the success value and panics if Err

Use this only when you’re confident that it won’t error or in test environment.


  1. Using the ? syntax

This passes the error up. So your function needs to be able to return an error, too (either a Result or an Option)

See this for example and its equivalent

Ownership & References

Heard of the borrow checker? Nothing much for me to say here. It’s the hardest thing on this list since it’s unique to rust. And if you’ve never handled references before, this topic might be a bit steep.


Thankfully the rust book saves the day once again

Basically: Read part 4.1, 4.2 and 4.3

And that’s it!

This list is actually shorter than I expected. I hope it’s useful for your journey.

See a mistake or have any suggestions? Let me know!


Like what you see here? Find more of my post or check my startup.


Also Published Here