You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: README.md
+18-14Lines changed: 18 additions & 14 deletions
Original file line number
Diff line number
Diff line change
@@ -2,11 +2,15 @@
2
2
3
3
> An introduction to the Rust programming language for Node developers.
4
4
5
-
Hi there, [I'm a JavaScript developer](https://github.com/donaldpipowitch) who wants to learn Rust and as a part of this process I'll write here about my learnings. So what is Rust actually and **why should you learn it**? Rust is a systems programming language like C or C++, but with influences from functional programming languages and even scripting languages like JavaScript. It _feels_ very modern - which is no surprise, because it is a relatively young language. [It went 1.0 in 2015!](http://blog.rust-lang.org/2015/05/15/Rust-1.0.html)That doesn't only mean it is _fun to write_, because it has less clutter to carry around, it is also _fun to use_, because it has a modern toolchain with a great package manager. Rust's most unique feature is probably the compile-time safety check: it catches errors like segfaults without introducing a garbage collector. Or to phrase it differently: maximum safety with maximum performance.
5
+
> 💡 **2nd edition.** I initially wrote this tutorial in the summer of 2016. Rust 1.0 was roughly a year old back than. This tutorial stayed quite popular over time even though I haven't added new chapters. As years passed by the Rust (and Node) ecosystem evolved further and this tutorial wasn't up-to-date with all changes. With the recent release of [_"Rust 2018"_](https://blog.rust-lang.org/2018/12/06/Rust-1.31-and-rust-2018.html)(which I'll explain later in more depth) I took the opportunity to update this tutorial as well. Enjoy the read! 🎉
6
6
7
-
Probably even more important than its features is the ecosystem and the community behind the language. Rust really shines here - especially for people who love the web. It is **backed by Mozilla** and the **biggest real world project** written in Rust is probably [servo](https://github.com/servo/servo), a modern browser engine. servo is very modular - e.g. you can require its [HTML parser as a standalone module](https://github.com/servo/html5ever). Can you do that with any other browser engine? As far as I know... _no_. [Chances are pretty high](http://blog.rust-lang.org/2016/05/13/rustup.html)that Rust will become a good host platform for [wasm](https://github.com/webassembly) - the future binary format for the web.
7
+
Hi there, I'm Donald. [I'm a JavaScript developer](https://github.com/donaldpipowitch) who wants to learn Rust and as a part of this process I'll write here about my learnings. But what is Rust and **why do I want learn it**? Rust is a systems programming language like C or C++, but with influences from functional programming languages and even scripting languages like JavaScript. It _feels_ very modern - which is no surprise, because it is a relatively young language. [It went 1.0 in 2015!](http://blog.rust-lang.org/2015/05/15/Rust-1.0.html)That doesn't only mean it is _fun to write_, because it has less clutter to carry around, it is also _fun to use_, because it has a modern toolchain with a great package manager. Rust's most unique feature is probably the compile-time safety check: it catches errors like segfaults without introducing a garbage collector. Or to phrase it differently: maximum safety with maximum performance.
8
8
9
-
Before we dive into our setup we want to look at least once into a real Rust file:
9
+
Probably even more important than its features is the ecosystem and the community behind the language. Rust really shines here - especially for people who love the web. The language was (and still is) heavily influenced by developers from Mozilla. They have written [`servo`](https://github.com/servo/servo), a modern browser engine, in Rust and [parts of Firefox are now running Rust code](https://hacks.mozilla.org/2017/11/entering-the-quantum-era-how-firefox-got-fast-again-and-where-its-going-to-get-faster/). [Rust is also great for authoring WebAssembly code](https://www.rust-lang.org/what/wasm) (short: _Wasm_), a [binary format for the web](https://webassembly.org/), which is [supported in Firefox, Edge, Chrome and Safari](https://caniuse.com/#feat=wasm).
10
+
11
+
To summarize: Rust is a young modern language with a great tooling and ecosystem, good safety and performance promises and which can be used for a lot of different projects - from low level tasks to command line tools and even web projects.
12
+
13
+
Before we dive into our tutorial we want to look at least once into a real Rust file:
10
14
11
15
```rust
12
16
fnmain() {
@@ -16,28 +20,28 @@ fn main() {
16
20
17
21
The JavaScript equivalent _could roughly_ look like this:
18
22
19
-
```javascript
23
+
```js
20
24
functionmain() {
21
25
console.log('Hello World!');
22
26
}
23
27
```
24
28
25
29
Nothing too scary, right? The `!` behind `println` could be a bit confusing, but don't mind it for now. Just think of it as a special function.
26
30
27
-
How do we move on from here? First I'll guide you how my current setup looks like to use Node and Rust. After that I'll create several kitchen sink like examples - first with Node and then with Rust. I'll try to explain them as best as I can, but _don't_ expect in-depth explanations in every case. Don't forget that I'm trying to learn Rust - _just like you_. Probably you need to explain _me_ some things, too! Oh, and before I forget it: my Node examples will be written in [TypeScript](https://www.typescriptlang.org/) actually! I think it makes some examples easier to compare to Rust and if you experience sweet type safety from Rust you want a little bit of that in your Node projects anyway ;)
31
+
How do we move on from here? First I'll guide you how my current setup looks like to use Node and Rust. Many people seemed to like that I introduce some convenient tooling and IDE configurations _before_ actually speaking about Rust itself. But you can skip this chapter, if you want. After the setup step I'll create several kitchen sink like examples - first with Node and then with Rust. I'll try to explain them as best as I can, but _don't_ expect in-depth explanations in every case. Don't forget that I'm trying to learn Rust - _just like you_. Probably you need to explain _me_ some things, too! And before I forget it: my Node examples will be written in [TypeScript](https://www.typescriptlang.org/)! Writing them in TypeScript will make it a little bit easier to compare some examples to Rust.
28
32
29
-
I try to add an example every two weeks.
33
+
One word about the structure of this tutorial before we start. Every chapter has its own directory. If a chapter has sub-chapters they also have sub-directories. And if a (subd-)chapter contains code examples, you'll find a `node` and a `rust` directory which contain all the code of this (sub-)chapter. (One example: The chapter [_"Package Manager"_](package-manager/README.md) can be found inside [`package-manager/`](package-manager). It has the sub-chapter [_"Publishing"_](package-manager/README.md#publishing) and the corresponding code examples can be found in [`package-manager/publishing/node/`](package-manager/publishing/node) and [`package-manager/publishing/rust/`](package-manager/publishing/rust).)
30
34
31
35
# Table of contents
32
36
33
-
0.[Setup](setup/README.md)
34
-
0.[Hello World](hello-world/README.md)
35
-
0.[Package Manager](package-manager/README.md)
36
-
0.[Read files](read-files/README.md)
37
-
0.[Write files](write-files/README.md)
38
-
0.[HTTP requests](http-requests/README.md)
39
-
0.[Parse JSON](parse-json/README.md)
37
+
1.[Setup](setup/README.md)
38
+
2.[Hello World](hello-world/README.md)
39
+
3.[Package Manager](package-manager/README.md)
40
+
4.[Read files](read-files/README.md)
41
+
5.[Write files](write-files/README.md)
42
+
6.[HTTP requests](http-requests/README.md)
43
+
7.[Parse JSON](parse-json/README.md)
40
44
41
-
Thank you for reading this article. ♥
45
+
Thank you for reading this tutorial. ♥
42
46
43
47
I highly appreciate pull requests for grammar and spelling fixes as I'm not a native speaker. Thank you!
Copy file name to clipboardExpand all lines: hello-world/README.md
+8-8Lines changed: 8 additions & 8 deletions
Original file line number
Diff line number
Diff line change
@@ -2,9 +2,9 @@
2
2
3
3
Ah, yes! A classic _"Hello world!"_ example. This one will be really quick, but I'll show you an important difference between Node and Rust.
4
4
5
-
Create a `hello-world.js` containing nothing more than this line:
5
+
Create a [`hello-world.js`](hello-world/node/hello-world.js) containing nothing more than this line:
6
6
7
-
```javascript
7
+
```js
8
8
console.log('Hello world!');
9
9
```
10
10
@@ -17,31 +17,31 @@ Hello world!
17
17
18
18
_Yeah!_ You'll see `Hello world!` in your console.
19
19
20
-
Now we'll do the same for Rust. Create a `hello_world.rs` with the followind content:
20
+
Now we'll do the same for Rust. Create a [`hello_world.rs`](hello-world/rust/hello_world.rs) with the following content:
21
21
22
22
```rust
23
23
fnmain() {
24
24
println!("Hello world!");
25
25
}
26
26
```
27
27
28
-
Rust actually needs a special entry point to execute code. This is our `main` function and as you can see a function in Rust is declared like in JavaScript, just with the `fn` keyword instead of `function`. It is important to call the function `main` or the Rust compiler will throw an error. In Rust we typically use 4 spaces to indent code inside a function. In JavaScript most projects I know (and [the Standard Style](https://github.com/feross/standard)) use 2 spaces. Rust also recommends `snake_case` naming style for directories and files while I think `kebab-case` is most common in JavaScript projects. `println` isn't a simple function call, but a macro - which is indicated by the `!`. For now think of a macro as some code which is transformed into other code at compile time. Last but not least you _need_ to wrap your string inside `"`, not `'`. In JavaScript there is no difference between `"` and `'` to create strings and [many](https://github.com/feross/standard) prefer to use `'`. In Rust a `"` creates a _string literal_ while `'` creates a _character literal_ which means it only accepts a single character. You could write `println!("H");` or `println!('H');` and both would compile, but `println!('Hello World!');` throws an error.
28
+
Rust actually needs a special entry point to execute code. This is our `main` function and as you can see a function in Rust is declared like in JavaScript, but with the `fn` keyword instead of `function`. It is important to call the function `main` or the Rust compiler will throw an error. In Rust we typically use 4 spaces to indent code inside a function, while 2 spaces are more common for JavaScript projects. (But thankfully this is covered by prettier anyway and it could be covered by `rustfmt` when [my feature request will be solved](https://github.com/rust-lang/rls/issues/1198).) Rust also recommends `snake_case` naming style for directories and files while I think `kebab-case` is most common in JavaScript projects. `println` isn't a simple function call, but a macro - which is indicated by the `!`. For now think of a macro as some code which is transformed into other code at compile time. Last but not least you _need_ to wrap your string inside `"`, not `'`. In JavaScript there is no difference between `"` and `'` to create strings (and [many](https://github.com/feross/standard) prefer to use `'`, even though it's not prettiers default). In Rust a `"` creates a _string literal_ while `'` creates a _character literal_ which means it only accepts a _single character_. You could write `println!("H");` or `println!('H');` and both would compile, but `println!('Hello World!');` throws an error.
29
29
30
30
Now compile our code with the following command:
31
31
32
32
```bash
33
33
$ rustc hello-word.rs
34
34
```
35
35
36
-
You'll see... nothing on your console. Instead a new file called `hello-world` was created next to `hello-world.rs`. This is our compiled code. You can run it like this:
36
+
You'll see... nothing on your console. Instead a new file called `hello-world` was created next to `hello-world.rs`. This file contains our compiled code. You can run it like this:
37
37
38
38
```bash
39
39
$ ./hello-world
40
40
Hello world!
41
41
```
42
42
43
-
Now you'll see `Hello world!` in your console. This shows a fundamental difference between JavaScript/Node and Rust. Rust needs to be compiled before our program can be executed. This extra step is not needed for JavaScript which makes the development cycle with JavaScript sometimes faster. However the compilation step catches a ton of bugs _before_ even executing your program. This can be _so_ useful that you probably often want to introduce something similar to JavaScript - like TypeScript. There is another big benefit: we can easily share our compiled `hello-world` program with other developers _without_ the need for them to have Rust installed. This is not possible with Node scripts. Everyone who wants to run our `hello-world.js` needs to have Node installed.
43
+
Now you'll see `Hello world!` in your console. This shows a fundamental difference between JavaScript/Node and Rust. Rust needs to be compiled before our program can be executed. This extra step is not needed for JavaScript which makes the development cycle with JavaScript sometimes faster. However the compilation step catches a ton of bugs _before_ even executing your program. This can be _so_ useful that you probably want to introduce a similar sanity check to JavaScript - for example by using TypeScript. There is another big benefit: we can easily share our compiled `hello-world` program with other developers _without_ the need for them to have Rust installed. This is not possible with Node scripts. Everyone who wants to run our `hello-world.js` needs to have Node installed and in a version which is supported by our script.
We import the `get` function from `https`. We declare a `host` and `path` (no need to set the protocol, when we already use the `https` module). After that we call `get` and pass an options object (containing our `host` and `path`) and callback whic accepts a response object (`res`) as the _first_ parameter. Yes, `get` doesn't follow the usual callback style pattern of Node where the first param is an error and the second param is a result. It is more low level than that. Instead we have an request object (the return value of `get`) and an response object (`res`) which are both event emitters. We listen for `error` events on the request object and in case of an error we just `throw``Couldn't send request.` to exit our program.
@@ -240,7 +242,7 @@ After that we read our result into a buffer (`buf`) and print the response body.
240
242
If you run our program now you see the same error as in our first Node example:
241
243
242
244
```
243
-
$ cargo run -q
245
+
$ cargo -q run
244
246
Response: Request forbidden by administrative rules. Please make sure your request has a User-Agent header (http://developer.github.com/v3/#user-agent-required). Check https://developer.github.com for other possible causes.
245
247
```
246
248
@@ -278,7 +280,7 @@ Note that we use an `if` statement in Rust for the first time. Unlike JavaScript
278
280
Test the program again:
279
281
280
282
```
281
-
$ cargo run -q
283
+
$ cargo -q run
282
284
Response: Request forbidden by administrative rules. Please make sure your request has a User-Agent header (http://developer.github.com/v3/#user-agent-required). Check https://developer.github.com for other possible causes.
283
285
284
286
thread '<main>' panicked at 'Got client error: 403 Forbidden', src/main.rs:50
@@ -332,12 +334,12 @@ We import `Headers` and `UserAgent` from `hyper::header`. We create a new instan
332
334
The last thing we need to do is passing our `headers` to our actually request with the `headers` method, just before we call `send`. Done!
0 commit comments