If you are a JavaScript programmer, this article will take you quickly to understand the many languages of the Rust programming language. There are many zero-based tutorials on Rust online, but since you’re already a programmer, why not compare it with a programming language you’re already familiar with?
Before you dive into Rust, listen to me explain the similarities and differences between it and JavaScript, and my introduction will be concise.
Disclaimer
I definitely can’t say I’m proficient in Rust. I try to do my best. Rust’s own documentation is rich and extensive, and you can refer to this knowledge if you want to dig deeper. My purpose is to list some key points, some of the most commonly encountered concepts, knowledge in programming, focusing on the comparison with what you already know in JavaScript. This will save you from repeating studies and save time.
variable type
Rust is a typed programming language that is very close to the TypeScript language. If you know TypeScript, it will help a lot to master the Rust language.
Basically its definition syntax is ( variable_name: Type ) like this!
snake_case
Yep, no getting around it.
What do these symbols do?
1. Question mark ( ? )
You will see a ? : my_function()?;
after some function calls.
This question mark does not mean optional. It’s an exception catch handler for a function that will throw an error. I will talk in detail later.
2. Exclamation mark ( ! ) in function
Example: println!("{:?}", my_variable);
It says this is a macro . JavaScript has nothing like this. A macro is something that writes some code to output some other code. You can think of it as a kind of syntactic sugar. Usage is like the example above.
3. Symbol &
Example: &your_variable
Get citations. If you use a low-level language, such as C, I believe you will understand this. Discuss later.
grammar
fn foo(num: i32) -> i32 { 3 // See no.2 // or // return 3; }
- Decorator syntax is also different . It’s also called Attributes.
some keywords
struct
is a JSON object. (Well, it might be a bit more complicated, see the documentation)
type Person = { firstName: string; lastName: string; };
struct Person { first_name: String, last_name: String, }
trait
impl
The closest thing to a trait’s interface implementation in JavaScript is Classes.
enum
The same way as the enumeration enums in Typescript. You can store some data in it. It is a very important concept when learning about async.
Console.log
It’s not hard to understand in JavaScript. More like printf in C language.
println!("{:?}", my_variable);
Codebase/Associated Dependencies
Use Cargo.toml
instead of package.json
. You’ll want to add them manually (instead of using a command like yarn add
)
Example:
[dependencies] chrono = "0.4" egg-mode = "0.16.0"
input
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 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 are 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 a 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 barebones 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
.
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:
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.
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 in 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!
English original: Rust from 0 to 80% for JavaScript Developers
This article is reprinted from https://www.techug.com/post/rust-from-0-to-80-for-js-dev/
This site is for inclusion only, and the copyright belongs to the original author.