TranslateProject/sources/tech/20220113 Learn Rust in 2022.md
DarkSun 20b92bee96 选题[tech]: 20220113 Learn Rust in 2022
sources/tech/20220113 Learn Rust in 2022.md
2022-01-14 05:02:27 +08:00

9.5 KiB

Learn Rust in 2022

If you're going to explore Rust this year, download our free Rust cheat sheet, so you have a quick reference for the basics. Cheat Sheet cover image

Rust is a relatively new programming language, and it's already a popular one winning over programmers from all industries. Still, it's also a language that builds on everything that's come before. Rust wasn't made in a day, after all, so even though there are concepts in Rust that seem wildly different from what you might have learned from Python, Java, C++, and so on, they all have a foundation in the same CPU and NUMA architecture you've always been (whether you know it or not) interacting with, and so some of what's new in Rust feels somehow familiar.

Now, I'm not a programmer by trade. I'm impatient yet obsessive. If a language doesn't help me get the results I want relatively quickly, I rarely find myself inspired to use it when I need to get something done. Rust tries to bring into balance two conflicting things: The modern computer's need for secure and structured code, and the modern programmer's desire to do less work while attaining more success.

Install Rust

The rust-lang.org website has great documentation on installing Rust, but usually, it's as simple as downloading the sh.rustup.rs script and running it.



$ curl --proto '=https' --tlsv1.2 -sSf <https://sh.rustup.rs>

$ less sh.rustup.sh

$ sh ./sh.rustup.rs

No classes

Rust doesn't have classes and does not use the class keyword. Rust does have the struct data type, however, its purpose is to serve as a kind of template for a collection of data. So instead of creating a class to represent a virtual object, you can use a struct:



struct Penguin {
    genus: String,
    species: String,
    extinct: bool,
    classified: u64,
}

You can use this similar to how a class is used. For instance, once a Penguin struct is defined, you can create instances of it, and interact with that instance:



struct Penguin {
    genus: String,
    species: String,
    extinct: bool,
    classified: u64,
}

fn main() {
    let p = Penguin { genus: "Pygoscelis".to_owned(),
         species: "R adeliæ".to_owned(), 
         extinct: false, 
         classified: 1841 };

    println!("Species: {}", p.species);    
    println!("Genus: {}", p.genus);
    println!("Classified in {}", p.classified);
    if p.extinct == true {
        println!("Sadly this penguin has been made extinct.");
    }
    
}

Using the impl data type in conjunction with the struct data type, you can implement a struct containing functions, and you can add inheritance and other class-like features.

Functions

Functions in Rust are a lot like functions in other languages. Each one represents a discreet set of tasks that you can call upon when needed. The primary function must be called main.

Functions are declared using the fn keyword, followed by the function's name and any parameters the function accepts.



fn foo() {
  let n = 8;
  println!("Eight is written as {}", n);
}

Passing information from one function to another gets done with parameters. For instance, I've already created a Penguin class, and I've got an instance of a penguin as p, so passing the attributes of p from one function to another requires me to specify p as an accepted Penguin type for its destination function.



fn main() {
  let p = Penguin { genus: "Pygoscelis".to_owned(), 
    species: "R adeliæ".to_owned(), 
    extinct: false, classified: 1841 };
  printer(p);
}

fn printer(p: Penguin) {
  println!("Species: {}", p.species);    
  println!("Genus: {}", p.genus);
  println!("Classified in {}", p.classified);
  if p.extinct == true {
      println!("Sadly this penguin has been made extinct.");
  }
}

Variables 

Rust creates immutable variables by default. That means that a variable you create cannot be changed later. This code, humble though it may be, cannot be compiled:



fn main() {
 let n = 6;
 let n = 5;
 }

However, you can declare a mutable variable with the keyword mut, so this code compiles successfully:



fn main() {
 let mut n = 6;
 println!("Value is {}", n);
 n = 5;
 println!("Value is {}", n);
}

Compiler 

The Rust compiler, at least in terms of its error messages, is one of the nicest compilers available. When you get something wrong in Rust, the compiler makes a sincere effort to tell you what you did wrong. I've actually learned many nuances of Rust (insofar as I understand any nuance of Rust) just by learning from compiler error messages. Even when an error message is too obscure to learn from directly, it's almost always enough for an internet search to explain.

The easiest way to start a Rust program is to use cargo, the Rust package management and build system.



$ mkdir myproject
$ cd myproject
$ cargo init 

This creates the basic infrastructure for a project, most notably a main.rs file in the src subdirectory. Open this file and paste in the example code I've generated for this article:



struct Penguin {
    genus: String,
    species: String,
    extinct: bool,
    classified: u64,
}

fn main() {
    let p = Penguin { genus: "Pygoscelis".to_owned(), species: "R adeliæ".to_owned(), extinct: false, classified: 1841 };
    printer(p);
    foo();
}

fn printer(p: Penguin) {
    println!("Species: {}", p.species);    
    println!("Genus: {}", p.genus);
    println!("Classified in {}", p.classified);
    if p.extinct == true {
        println!("Sadly this penguin has been made extinct.");
    }
}

fn foo() {
     let mut n = 6;
 println!("Value is {}", n);
 n = 8;
  println!("Eight is written as {}", n);
}

To compile, use the cargo build command:

`$ cargo build`

To run your project, execute the binary in the target subdirectory, or else just use cargo run



$ cargo run
Species: R adeliæ
Genus: Pygoscelis
Classified in 1841
Value is 6
Eight is written as 8

Crates

Much of the convenience of any language comes from its libraries or modules. In Rust, libraries get distributed and tracked as "crates". The crates.io website is a good registry of community crates.

To add a crate to your Rust project, list them in the Cargo.toml file. For instance, to install a random number function, I use the rand crate, with * serving as a wildcard to ensure that I get the latest version at compile time:



[package]
name = "myproject"
version = "0.1.0"
authors = ["Seth &lt;[seth@opensource.com][5]&gt;"]
edition = "2022"

[dependencies]
rand = "*"

Using it in Rust code requires a use statement at the top:

`use rand::Rng;`

Some sample code that creates a random seed and then a random range:



fn foo() {
    let mut rng = rand::thread_rng();
    let mut n = rng.gen_range(1..99);

    println!("Value is {}", n);
    n = rng.gen_range(1..99);
    println!("Value is {}", n);
}

You can use cargo run to run it, which detects the code change and triggers a new build. The build process downloads the rand crate and all the crates that it, in turn, depends upon, compiles the code, and then runs it:



$ cargo run
Updating crates.io index
Downloaded ppv-lite86 v0.2.16
Downloaded 1 crate (22.2 KB) in 1.40s
 Compiling libc v0.2.112
 Compiling cfg-if v1.0.0
 Compiling ppv-lite86 v0.2.16
 Compiling getrandom v0.2.3
 Compiling rand_core v0.6.3
 Compiling rand_chacha v0.3.1
 Compiling rand v0.8.4
 Compiling rustpenguin v0.1.0 (/home/sek/Demo/rustpenguin)
 Finished dev [unoptimized + debuginfo] target(s) in 13.97s
 Running `target/debug/rustpenguin`

Species: R adeliæ
Genus: Pygoscelis
Classified in 1841
Value is 70
Value is 35

Rust cheat sheet

Rust is a supremely pleasant language. Thanks to its integration with online registries, its helpful compiler, and its almost intuitive syntax, it feels appropriately modern.

Make no mistake, though, it's also a complex language, with strict data types, strongly scoped variables, and many built-in methods. Rust is worth looking at, and if you're going to explore Rust, then you should download our free Rust cheat sheet, so you have a quick reference for the basics. The sooner you get started, the sooner you'll know Rust. And, of course, you should practice often to avoid getting rusty.


via: https://opensource.com/article/22/1/rust-cheat-sheet

作者:Seth Kenlon 选题:lujun9972 译者:译者ID 校对:校对者ID

本文由 LCTT 原创编译,Linux中国 荣誉推出