Rust tutorial: introduction to rust for JavaScript developers

Dunib 2021-02-23 02:00:27
rust tutorial introduction rust javascript


Rust yes 2010 It originated in Mozilla Research A programming language for . Now , All the big companies are using it .

Both Amazon and Microsoft recognize it as part of their system C / C ++ The best alternative to , however Rust It's not just that . image Figma and Discord Such companies now also use it in client applications Rust To lead the trend .

This article Rust The purpose of the tutorial is to give a brief introduction to Rust, How to use it in a browser , And when to consider using it . I'll start with comparison Rust and JavaScript Start , And then lead you through Rust Steps to run in the browser . Last , I'm going to introduce a way to use Rust and JavaScript Of COVID simulator web Fast performance evaluation of applications .

In short

Rust Conceptually with JavaScript Very different . But there are similarities to point out , Let's look at both sides of the problem .

Similarity

Both languages have a modern package management system .JavaScript Yes npm,Rust Yes Cargo.Rust Yes Cargo.toml Instead of package.json Manage dependencies . To create a new project , Use cargo init, To run it , Use cargo run. It's not strange, is it ?

Rust There are many cool features in , You've gone from JavaScript I got it in the game , Only the grammar is slightly different . Take advantage of this common JavaScript Pattern , Apply a closure to each element in the array :

let staff = [
{ name: "George", money: 0 },
{ name: "Lea", money: 500000 },
];
let salary = 1000;
staff.forEach((employee) => {
employee.money += salary;
});

stay Rust in , We can write this way :

let salary = 1000;
staff.iter_mut().for_each(
|employee| { employee.money += salary; }
);

indeed , It takes time to get used to this grammar , Use a tube ( | ) Replace brackets . But after overcoming the initial embarrassment , I found it read more clearly than another set of brackets .

Another example , This is a JavaScript Object deconstruction in :

let point = { x: 5, y: 10 };
let { x, y } = point;

Also in Rust in :

let point = Point { x: 5, y: 10 };
let Point { x, y } = point;

The main difference is , stay Rust We must specify the type in (Point), More generally ,Rust All types need to be known at compile time . But unlike most other compiled languages , The compiler infers types as much as possible .

To further explain the problem , The following is the C++ And many other languages . Each variable requires an explicit type declaration .

int a = 5;
float b = 0.5;
float c = 1.5 * a;

stay JavaScript as well as Rust in , This code is valid :

let a = 5;
let b = 0.5;
let c = 1.5 * a;

There are so many shared functions :

  • Rust have async + await grammar .
  • Arrays can be like let array = [1,2,3] Just as easy to create .
  • Codes are organized by modules , There is a clear import and export .
  • String is used Unicode Coded , There is no problem with special characters .

I can go on , But I think my point is clear now .Rust It has a series of rich functions , These functions are very important in modern society JavaScript Also used in .

Difference

Rust It's a compiler language , This means that no runtime can execute Rust Code . An application can only run in the compiler (rustc) Run it after finishing its magic . The benefit of this approach is usually better performance .

Fortunately, ,Cargo It solves the problem of calling compiler for us . And with webpack, We can also put Cargo Hidden in npm run build Back . With this guide , Just set it up for the project Rust, You can keep Web Normal workflow of developers .

Rust Is a strong type of language , This means that at compile time all types must match . for example , You can't call a function with the wrong type or number of arguments . The compiler will catch this error for you before you run into it . The obvious comparison is TypeScript, If you like TypeScript, Then you're likely to like it Rust.

But don't worry : If you don't like it TypeScript,Rust Maybe it's still for you .Rust It was built from scratch in recent years , It takes into account everything that humans have learned in programming language design over the past few decades . The result is a refreshing and concise language .

Rust Pattern matching in is one of my favorite features , Other languages are switch and case To avoid long chains like this :

if (x == 1) {
// ...
} else if (x == 2) {
// ...
} else if (x == 3 || x == 4) {
// ...
} // ...

Rust The following more elegant matches are used :

match x {
1 => { /* Do something if x == 1 */},
2 => { /* Do something if x == 2 */},
3 | 4 => { /* Do something if x == 3 || x == 4 */},
5...10 => { /* Do something if x >= 5 && x <= 10 */},
_ => { /* Catch all other cases */ }
}

I think it's very neat , I hope JavaScript Developers can also appreciate this syntax extension .

Unfortunately , We have to talk about it Rust The dark side of . To speak out , Using a strict type system can sometimes feel very cumbersome . If you think C++ or Java The type system is very strict , So please be ready for it Rust Let's have a hard journey .

As far as I'm concerned , I am very fond of Rust This part . I rely on a strict type system , So you can turn off a part of the brain —— Whenever I find myself writing JavaScript when , A part of the brain is excited violently . But I know for beginners , It's annoying to always fight the compiler . We'll be in later Rust You can see some in the tutorial .

Hello Rust

Now? , Let's use it Rust Run a hello world , We first need to make sure that all the necessary tools are installed .

Tools

Use rustup install Cargo + rustc. Rustup Is the recommended installation Rust Methods , It will install the latest stable version Rust The compiler (rustc) And package manager (Cargo). It will install Rust The latest stable version of the compiler (rustc) And package manager (Cargo). It can also be managed beta Version and nightly build , But for this example , This is not necessary .

  • Input on the terminal cargo --version To check the installation , You should be able to see cargo 1.48.0 (65cbdd2dc 2020-10-14) Such content .
  • And check Rustup:rustup --version Should produce rustup 1.23.0(00924c9ba 2020-11-27).

install wasm-pack. This is to integrate the compiler with the npm Integrate .

  • By input wasm-pack --version To check the installation , This should be for you wasm-pack 0.9.1 Things like that .

We also need Node and npm. We have a complete article article Explains the best way to install both .

To write Rust Code

Now it's all set up , Let's create a project . The final code can also be found here GitHub Warehouse Find . We build from a npm Bag Rust Project start , The package will be imported later JavaScript Code .

To create a hello-world Of Rust project , Please use cargo init --lib hello-world. This creates a new directory and generates the Rust All files required by the library :

├──hello-world
├── Cargo.toml
├── src
├── lib.rs

Rust The code will be placed in the lib.rs in , Before that, we have to adjust Cargo.toml. It USES TOML The dependencies and other package information are defined . If you want to see it in the browser hello world, Please be there. Cargo.toml Add the following number of rows somewhere in ( for example , At the end of the file ).

[lib]
crate-type = ["cdylib"]

This tells the compiler to C Create a library in compatibility mode . Obviously we didn't use it in our example C.C-compatible It just means it's not Rust A dedicated , This is what we use JavaScript Required by the library in .

We also need two external libraries , Add them as a separate line to the dependencies section .

[dependencies]
wasm-bindgen = "0.2.68"
web-sys = {version = "0.3.45", features = ["console"]}

These are all from crates.io The dependencies of , It is Cargo Default package warehouse used .

wasm-bindgen be necessary , To create one that we can get from later JavaScript Entrance point of call .( You can find the complete documentation here .) value ”0.2.68" Specified version .

web-sys It includes everything Web API Of Rust binding , It will give us access to the browser console . Please note that , We have to choose the console function explicitly , Our final binary will contain only the ones selected in this way Web API binding .

Next is lib.rs Internal actual code . Automatically generated unit tests can be deleted . Just replace the contents of the file with the following code :

use wasm_bindgen::prelude::*;
use web_sys::console;
#[wasm_bindgen]
pub fn hello_world() {
console::log_1("Hello world");
}

At the top of the use Statement is used to import projects from other modules . This is related to JavaScript Medium import similar ).

pub fn hello_world(){...} Declare a function . pub The modifier is “public” Abbreviation , Function like JavaScript Medium export. notes #[wasm_bindgen] Specific to Rust Compiled into WebAssembly (Wasm)")"). We need it here to make sure that the compiler exposes the wrapper function to JavaScript.

In the functional subject ,“Hello world” It's printed on the console . Rust Medium console :: log_1() It's right console.log() Wrapper for call to .

Have you noticed any errors in function calls _1 suffix ? This is because JavaScript A variable number of parameters are allowed , and Rust Don't allow . To solve this problem , wasm_bindgen Generate a function for each number of arguments . Yes , It's going to get ugly soon ! But it works . stay web-sys file Provides a Rust List of complete functions called in the console .

By now we should have everything in place , Try compiling it with the following command . This will download all the dependencies and compile the project , The first time may take some time .

cd hello-world
wasm-pack build

Ha !Rust The compiler is not satisfied with us .

error[E0308]: mismatched types
--> src\lib.rs:6:20
|
6 | console::log_1("Hello world");
| ^^^^^^^^^^^^^ expected struct `JsValue`, found `str`
|
= note: expected reference `&JsValue`
found reference `&'static str

Be careful : If you see other errors (error: linking with cc failed: exit code: 1) And you use Linux, Cross compilation dependency is missing . sudo apt install gcc-multilib It should solve this problem .

As I mentioned earlier , The compiler is very strict . When it expects one JsValue When a reference to is used as an argument to a function , It does not accept a static string . In order to meet the requirements of the compiler , Explicit conversion is required .

console::log_1(&"Hello world".into());

Method into()")") Converts one value to another .Rust Compilers are smart , Which types can it delay participating in the conversion , Because functional signatures leave only one possibility . under these circumstances , It will be converted to JsValue, This is a result of JavaScript The wrapper type of the managed value . then , We have to add more &, Pass by reference, not by value , Otherwise, the compiler will complain again .

Try running again wasm-pack build, If all goes well , Then the last line should look like this :

[INFO]: :-) Your wasm pkg is ready to publish at /home/username/intro-to-rust/hello-world/pkg.

If you can get to this point , You can compile it manually now Rust 了 . next step , We're going to combine it with npm and webpack Integrate , The latter will automatically complete the work for us .

JavaScript Integrate

In this case , I decided to package.json Put it in hello-world In the table of contents . We can also for Rust The project and JavaScript Projects use different directories , It's a matter of taste .

The following is mine package.json file . The easiest way to follow is to copy it and run it npm install, Or run npm init And copy only dev Dependencies :

{
"name": "hello-world",
"version": "1.0.0",
"description": "Hello world app for Rust in the browser.",
"main": "index.js",
"scripts": {
"build": "webpack",
"serve": "webpack serve"
},
"author": "Jakob Meier <inbox@jakobmeier.ch>",
"license": "(MIT OR Apache-2.0)",
"devDependencies": {
"@wasm-tool/wasm-pack-plugin": "~1.3.1",
"@webpack-cli/serve": "^1.1.0",
"css-loader": "^5.0.1",
"style-loader": "^2.0.0",
"webpack": "~5.8.0",
"webpack-cli": "~4.2.0",
"webpack-dev-server": "~3.11.0"
}
}

As you can see , We use webpack 5.Wasm-pack It can also be compared with the old version webpack Use it together , You don't even need to use a bundle . But each setting works a little differently , I suggest you follow this Rust Use exactly the same version for the tutorial .

Another important dependency is wasm-pack-plugin. This is a Webpack plug-in unit , It is specially used for loading wasm-pack Built Rust software package .

continue , We also need to create webpack.config.js File to configure webpack. It should be like this :

const path = require("path");
const webpack = require("webpack");
const WasmPackPlugin = require("@wasm-tool/wasm-pack-plugin");
module.exports = {
entry: "./src/index.js",
output: {
path: path.resolve(__dirname, "dist"),
filename: "index.js",
},
plugins: [
new WasmPackPlugin({
crateDirectory: path.resolve(__dirname, "."),
}),
],
devServer: {
contentBase: "./src",
hot: true,
},
module: {
rules: [
{
test: /\.css$/i,
use: ["style-loader", "css-loader"],
},
],
},
experiments: {
syncWebAssembly: true,
},
};

All paths are configured to Rust Code and JavaScript Code side by side .index.js Will be in src In the folder , Next to each other lib.rs. If you like different settings , These can be adjusted at any time .

You will also notice , We use webpack experiments, This is a webpack 5 New options introduced . Please ensure that the syncWebAssembly Set to true.

Last , We have to create JavaScript entry point src/index.js

import("../pkg")
.catch((e) =>
console.error("Failed loading Wasm module:", e)
)
.then((rust) => rust.hello_world());

We have to load asynchronously Rust modular . call rust.hello_world() A generated wrapper function is called , And this function calls lib.rs As defined in Rust function hello_world.

Now? , function npm run serve You should be able to compile everything and start the development server . We don't define HTML file , So there is no display on the page . You may also have to go to the http://localhost:8080/index, because http://localhost:8080 Just list the files without executing any code .

After opening a blank page , Open the developer console . Hello World There should be a log entry .

ok , For a simple hello world Come on , It's quite a lot of work . But now it's all in place , We can easily expand Rust Code , And don't worry about it . Save pairs lib.rs After the modification of , You should automatically see recompilation and live updates in the browser , It's like JavaScript equally .

When to use Rust

Rust No JavaScript General alternatives to . It can only pass through Wasm Run... In a browser , This largely limits its role . Even if you can use it Rust Replace almost all JavaScript Code , If you really want to , That's a bad idea , And it's not Wasm Purpose . for example ,Rust It's not suitable for your website UI Interact .

In my submission Rust + Wasm It's an extra option , Can be used to run more efficiently CPU Heavy workload . At the cost of large Downloads ,Wasm Avoided JavaScript Code analysis and compilation overhead . This point , Plus the powerful optimization of compiler , May lead to better performance . This is usually the company's choice for a specific project Rust Why . choice Rust Another reason may be language preference , But this is a completely different discussion , I won't discuss it here .

版权声明
本文为[Dunib]所创,转载请带上原文链接,感谢
https://qdmana.com/2021/02/20210222205258572h.html

  1. vue判断elementui中el-form是否更新变化,变化就提示是否保存,没变就直接离开
  2. 算法题:两数之和——JavaScript及Java实现
  3. 高性能 Nginx HTTPS 调优
  4. Why Vue uses asynchronous rendering
  5. day 31 jQuery进阶
  6. day 30 jQuery
  7. CSS whimsy -- using background to create all kinds of wonderful backgrounds
  8. Why are more and more people learning front end?
  9. What do you do with 4K front-end development?
  10. 8 years of front-end development knowledge precipitation (do not know how many words, keep writing it...)
  11. What is the annual salary of a good web front end?
  12. Front end novice tutorial! How to get started with web front end
  13. Will the front end have a future?
  14. Is the front end hard to learn?
  15. Seven new Vue combat skills to improve efficiency in 2021!
  16. Is front end learning difficult?
  17. How about the process of Web front-end development and self-study?
  18. Front end learning route from zero basis to proficient
  19. What is the basis of learning front end?
  20. What knowledge points need to be learned for self-study front end? How long can I become a front-end Engineer?
  21. An inexperienced front-end engineer, what are the common problems when writing CSS?
  22. HttpServletRequest get URL (parameter, path, port number, protocol, etc.) details
  23. Springboot starts http2
  24. Enabling http2.0 in spring boot
  25. JQuery:JQuery基本语法,JQuery选择器,JQuery DOM,综合案例 复选框,综合案例 随机图片
  26. Using JavaScript in Safari browser history.back () the page will not refresh after returning to the previous page
  27. vue.js Error in win10 NPM install
  28. In less than two months, musk made more than $1 billion, more than Tesla's annual profit
  29. Springboot starts http2
  30. Vue event bus
  31. JQuery easy UI tutorial: custom data grid Pagination
  32. Using okhttp and okhttpgo to obtain onenet cloud platform data
  33. Vue3 component (IX) Vue + element plus + JSON = dynamic rendering form control
  34. HTTP 1. X learning notes: an authoritative guide to Web Performance
  35. Vue3 component (IX) Vue + element plus + JSON = dynamic rendering form control
  36. HTTP 1. X learning notes: an authoritative guide to Web Performance
  37. JQuery:JQuery基本语法,JQuery选择器,JQuery DOM,综合案例 复选框,综合案例 随机图片
  38. Event bubble and capture in JavaScript
  39. The root element is missing solution
  40. Event bubble and capture in JavaScript
  41. Configure the certificate to enable ngnix to publish the trusted website of HTTPS
  42. Javascript数据类型
  43. HTTP interface debugging tool! 48000 star HTTP command line client!
  44. Parameter encryption of front end URL link band
  45. HTTP interface debugging tool! 48000 star HTTP command line client!
  46. Three front end frameworks: data binding and data flow
  47. Reading Axios source code (1) -- exploring the realization of basic ability
  48. Event bubble and capture in JavaScript
  49. 【微前端】微前端最終章-qiankun指南以及微前端整體探索
  50. R & D solution e-Car front end monitoring system
  51. [JS] 877 - 35 wonderful knowledge of JavaScript, long experience!
  52. R & D solution e-Car front end monitoring system
  53. High performance nginx HTTPS tuning - how to speed up HTTPS by 30%
  54. 解决ajax跨域问题【5种解决方案】
  55. Top ten classic sorting of JavaScript
  56. HTTP 1. X learning notes: an authoritative guide to Web Performance
  57. Vue3 component (IX) Vue + element plus + JSON = dynamic rendering form control component
  58. My http / 1.1 is so slow!
  59. Why Vue uses asynchronous rendering
  60. The response status was 0. Check out the W3C XMLHttpRequest Level 2 spec for