This article was first published on the official website of Luozhu, welcome to visit, reprint, please contact the author on wechat for authorization.

preface

Those of you who follow Luo Zhu recently know that I have become a Deno Contributor. Unfortunately, my PR has nothing to do with code logic. I was just in order to investigate Deno Github Action application, in writing ding, a Deno Github Action source code analysis please check the article in the process, accidentally found Deno CI fallacy and unreasonable. After consulting the opinions of the fandu bosses, I submitted my own PR. In order to participate in the core development of Deno, after a few days of ideological struggle, I decided to learn Rust.

If you ask me why I started learning Deno, Go, and Rust without being proficient in Node, I really can’t answer you, especially since I’m a front-end. What I can tell you is that if we had not started Deno and Go before, we would not have come up with a good plan when designing the management of CLI TPC and Tuya-Panel-Demo of our team.

Besides, as a computer major student, who hasn’t studied C/C++, Java, operating systems, data structures, computer principles? Although I didn’t learn it well and forgot about it, it was sufficient for learning any programming language by myself. At xiaoshuai’s suggestion, I will also pick up these basic theories to review. The Year of the Ox also calls for an open mind about a programmer’s career, rather than being plagued by artificial anxiety.

Why Rust?

Rust is a programming language that helps you develop efficient, reliable software. Compared to C/C++, Rust strives to provide both strong engineering capabilities and a good development experience, giving developers control over low-level capabilities (such as memory operations) while avoiding many of the pitfalls associated with traditional languages.

A high performance

Rust is surprisingly fast and memory efficient. With no runtime or garbage collection, it can be used for particularly high-performance services, run on embedded devices, and integrate easily with other languages.

reliability

Rust’s rich type system and ownership model guarantee memory safety and thread safety, allowing you to eliminate all kinds of errors at compile time.

productivity

Rust has excellent documentation, a friendly compiler, and clear error messages. It also integrates first-class tools — package manager and build tools, multi-editor support for auto-completion and type checking, automatic code formatting, and more.

Rust landing condition

Hundreds of companies around the world have used Rust in production environments to achieve fast, cross-platform, and low resource usage. Many well-known and popular apps like Firefox, Dropbox, and Cloudflare use Rust. From startups to large enterprises, from embedded devices to extensible Web services, Rust is perfectly suitable.

Dropbox

Multiple modules of Dropbox’s core file storage system were written in Rust because it was part of a larger project that sought greater data center efficiency. It currently works on all Dropbox storage systems and serves more than 500 million users.

Yelp

Yelp used Rust to develop A framework for real-time A/B testing. Widely used in all Yelp pages and apps, Rust was chosen because it’s as fast as C (cheap to run) and safer than C (easy to maintain).

Deno and Rust

Deno was originally Golang + TypeScript, but because of the GC problems with Golang and V8, Ryan made a big effort to replace Golang with Rust without GC. One answer made sense to Zhihu:

  1. Go has its own GCS, V8 has its own GCS, and how much of a performance penalty dual GCS and complex runs incur.
  2. Rust has high performance, memory safety and other features that make it ideal for writing high-performance programs.

Garbage Collector, Rust, and others do not have a Garbage Collector, but instead use a mechanism called ownership. Since this is an introduction, I will not expand it here.

Install the Rust

Unlike many others, Rust officially provides the Rustup command-line tool to download, install, and manage different Rust distributions and their accompanying toolchains.

Note: Rust’s stability ensures that all distributions are backward compatible.

Install rustup:

curl https://sh.rustup.rs -sSf | sh
Copy the code

Output:

$ curl https://sh.rustup.rs -sSf | sh
info: downloading installer

Welcome to Rust!

This will download and install the official compiler for the Rust
programming language, and its package manager, Cargo.

Rustup metadata and toolchains will be installed into the Rustup
home directory, located at:

  /Users/luozhu/.rustup

This can be modified with the RUSTUP_HOME environment variable.

The Cargo home directory located at:

  /Users/luozhu/.cargo

This can be modified with the CARGO_HOME environment variable.

The cargo, rustc, rustup and other commands will be added to
Cargo's bin directory, located at: /Users/luozhu/.cargo/bin This path will then be added to your PATH environment variable by modifying the profile files located at: /Users/luozhu/.profile /Users/luozhu/.zshenv You can uninstall at any time with rustup self uninstall and these changes will be reverted. Current installation options: default host triple: x86_64-apple-darwin default toolchain: stable (default) profile: default modify PATH variable: yes 1) Proceed with installation (default) 2) Customize installation 3) Cancel installation >1Copy the code

The above information can be summarized as:

  1. Rustup Home catalog:~/.rustup, you can useRUSTUP_HOMEEnvironment variable modification
  2. Cargo home catalogue:~/.cargo, you can useCARGO_HOMEEnvironment variable modification
  3. Cargo, rustC, Rustup and other commands are installed at~/.cargo/bin
  4. The PATH environment variable is placed in~/.zshenv(See this for the first time)

Here let’s choose the installation method. Since this is an entry point, we directly choose the default installation, and enter the following:

info: profile set to 'default'
info: default host triple is x86_64-apple-darwin
info: syncing channel updates for 'stable-x86_64-apple-darwin'Info: Latest Update on 2021-02-11, rust version 1.50.0 (CB75AD5DB 2021-02-10) info: downloading Component'cargo'4.3 MiB/ 4.3 MiB (100%) 3.1 MiB/sin  1s ETA:  0s
info: downloading component 'clippy'
info: downloading component 'rust-docs'14.7 MiB/ 14.7 MiB (100%) 2.2 MiB/sin  6s ETA:  0s
info: downloading component 'rust-std'23.3 MiB/ 23.3 MiB (100%) 2.2 MiB/sin 11s ETA:  0s
info: downloading component 'rustc'61.0 MiB/ 61.0 MiB (100%) 2.3 MiB/sin 26s ETA:  0s
info: downloading component 'rustfmt'
info: installing component 'cargo'Info: Using up to 500.0 MiB of RAM to unpack Components INFO: Installing Component'clippy'
info: installing component 'rust-docs'14.7 MiB/ 14.7 MiB (100%) 5.8 MiB/sin  1s ETA:  0s
info: installing component 'rust-std'23.3 MiB/ 23.3 MiB (100%) 13.0 MiB/sin  3s ETA:  0s
info: installing component 'rustc'61.0 MiB/ 61.0 MiB (100%) 13.3 MiB/sin  4s ETA:  0s
info: installing component 'rustfmt'
info: default toolchain set to 'stable-x86_64-apple-darwin'Stable - x86_64-apple-Darwin installed-rustc 1.50.0 (CB75AD5DB 2021-02-10) Rust is installed now. Great! To get started you need Cargo's bin directory ($HOME/.cargo/bin) in your PATH environment variable. Next time you log in this will be done automatically. To configure your current shell, run: source $HOME/.cargo/envCopy the code

This is the process of installing Rust and its toolchain and automatically setting up the environment. You can either enter source $HOME/.cargo/env as prompted for the configuration to take effect immediately or reopen a command line for the configuration to take effect.

Verify that the installation is successful:

rustc --version
Copy the code

If it goes well, you should see the output in rustc X.Y.Z (version hash yyyY-MM-DD) format.

Update:

rustup update
Copy the code

Uninstall:

rustup self uninstall
Copy the code

Local document

The installation tool will generate an offline document locally as it executes. You can open it in your browser by running the rustup doc command. But I don’t think it will be used in general. We install Rust plug-in in vscode with documentation prompt function.

Hello,World!

vscode

Install the Rust plug-in:

Rust-analyzer is also a good alternative, but not perfect yet!

Rust-client. rustupPath: “$HOME/.cargo/bin/rustup” is added to setting.json to fix the Couldn’t start Client Rust Language Server

To debug the software, install the CodeLLDB plug-in again:

Crates is a plug-in that helps developers manage dependencies when using Cargo. Toml

Since Cargo, Rust’s dependency management tool, uses TOML as its configuration file, you need to download the Better TOML plug-in to support syntax:

Finally, set automatic formatting when saving:

// settings.json
{
  "[rust]": {
    "editor.formatOnSave": true}}Copy the code

First line of code

Note: Rust files always end with rs. If you have more than one word in your name, you can use an underscore to separate them. For example, you’d better use hello_world.rs as the file name instead of helloworld.rs

Create a new main.rs and write the following code:

fn main() {
  println!("Hello,World!");
}
Copy the code
  • Using keywordsfnIt defines a function. (Go) (func), JS (function), mathematics (f), it looks like Rust saves fabric.
  • The main function is special: when you run an executable Rust program, all code runs from this entry function (same with Go).
  • As a rule, Rust recommends putting the open curly braces on the same line as the function declaration and separating them with a space.
  • We’re calling something calledprintln!Macros: If we were calling a normal function, this would be removed!The symbol ofprintlnTo tag.
  • Most Rust codes end with a semicolon.

Macro is a term for batch processing. A macro in computer science is an Abstraction that replaces certain text patterns according to a set of predefined rules. The interpreter or compiler automatically performs this pattern substitution when it encounters a macro. — can be simply understood as globally defined functions, variables, etc

You can run rustc main.rs on the command line to compile the code. When compiled successfully, the executable file main is generated:

.├ ── main ├─ ch.pdfCopy the code

Executing./main will output Hello,World!

In Windows, main.exe is generated

Unlike dynamic languages like Ruby, Python, or JavaScript, Rust, Go, and Deno are all compiled languages (JIT technology is out of the question), which means that when you compile Rust, you can deliver the executable to someone else. Run in an environment where Rust is not installed. If you develop an application using Node and deliver it to someone else, they must own the Node development environment.

Hello,Cargo!

As with Go build, the system’s build tools (RUSTC) are sufficient to compile simple programs, but they are not sufficient for large, collaborative developer projects. Go has GOX, GOXC, XGO, and Rust has Cargo to help us manage things like simplifying project dependencies, code building.

Cargo is a build system and package manager built into the Rust toolchain. Because it handles many trivial but important tasks such as building code, downloading and compiling dependent libraries, most Rust users choose it to manage their Rust projects (such as Deno).

In vsCode, the Rust plug-in will report the following error. Cargo is the standard configuration of Rust:

Create the project using Cargo

Cargo New hello_cargo

Cargo generated two files and a directory for us: a file named Cargo. Toml, and a source code file called main.rs, which was placed under the SRC directory. Cargo also initializes a new Git repository and elevates it to the default.gitignore file.

Cargo.toml

[package]
name = "hello_cargo"
version = "0.1.0 from"
authors = ["youngjuning <[email protected]>"]
edition = "2018"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
Copy the code
  • [package]: is a region label that indicates that the following statement will be used to configure the current package.authorThe mailbox and the name are from~/.gitconfigReads the
  • [dependencies]: is also a region tag that indicates that subsequent regions will be used to declare dependencies for the project.

TOML is intended to be a small, easy to use, semantic configuration file format, and the name “TOML” is an acronym for “Tom’s Obvious, Minimal Language.” “Tom” refers to its author, Tom Preston-Werner.

By default, Cargo stores all source code files in the SRC directory, and the project root directory is used only for non-source code files such as README documents, license notices, configuration files, and so on. Using Cargo can help you organize your project files rationally and consistently so that everything is in order.

Build and run the project using Cargo

cargo build
Copy the code

Unlike before, this command generates the executable under the path target/debug/hello_cargo:

Cargo build generates cargo. Lock (similar to yarn.lock) the first time you use the cargo build command. Do not modify this file manually. We copy the best practice from https://github.com/github/gitignore/blob/master/Rust.gitignore.

This is simply compiled and run using the cargo run command:

Cargo Check can also be used to quickly check if the item is compilable

Build in Release mode

cargo build --release
Copy the code

The generated executable will be placed in target/release instead of target/debug.

If you want to benchmark the efficiency of your code, build it with cargo run –release and benchmark it with the executable in target/release.

crate

In Rust, we refer to the collection of code as a package. Crate is the smallest compilation unit in Rust. A package is a collection of one or more Crate’s. Both Crate and package can be called a package because a single Crate is also a package. But packages generally favor a combination of crate’s. Crates. IO is the Crate agent for the Rust community.

Unfinished story

Part of this article is from Rust’s Authoritative Guide

After searching around and finding no Rust group, I made one of my own. Welcome to join:

Doodle Smart has a large number of high-quality HC, welcome to join, you need to add my wechat yang_jun_ning, or directly send your resume to [email protected]