[提交译文][tech]:20220113 Learn Rust in 2022

This commit is contained in:
hanszhao80 2022-05-04 21:38:00 +08:00
parent d4d1c17afe
commit 29b2e751fb
2 changed files with 329 additions and 329 deletions

View File

@ -1,329 +0,0 @@
[#]: subject: "Learn Rust in 2022"
[#]: via: "https://opensource.com/article/22/1/rust-cheat-sheet"
[#]: author: "Seth Kenlon https://opensource.com/users/seth"
[#]: collector: "lujun9972"
[#]: translator: "hanszhao80"
[#]: reviewer: " "
[#]: publisher: " "
[#]: url: " "
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][1]
Rust is a relatively new programming language, and it's already a popular one [winning over programmers][2] 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][3] 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][4] 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][6]**, 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][a]
选题:[lujun9972][b]
译者:[hanszhao80](https://github.com/hanszhao80)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
[a]: https://opensource.com/users/seth
[b]: https://github.com/lujun9972
[1]: https://opensource.com/sites/default/files/styles/image-full-size/public/lead-images/coverimage_cheat_sheet.png?itok=lYkNKieP (Cheat Sheet cover image)
[2]: https://opensource.com/article/20/5/rust-java
[3]: http://rust-lang.org
[4]: https://crates.io/
[5]: mailto:seth@opensource.com
[6]: https://opensource.com/downloads/rust-cheat-sheet

View File

@ -0,0 +1,329 @@
[#]: subject: "Learn Rust in 2022"
[#]: via: "https://opensource.com/article/22/1/rust-cheat-sheet"
[#]: author: "Seth Kenlon https://opensource.com/users/seth"
[#]: collector: "lujun9972"
[#]: translator: "hanszhao80"
[#]: reviewer: " "
[#]: publisher: " "
[#]: url: " "
在 2022 年学习 Rust
======
如果你打算在今年探索 Rust请下载我们的免费 Rust 速查表,以供快速参考基础知识。
![Cheat Sheet cover image][1]
Rust 是一门相对较新的编程语言,受到各个企业的 [程序员的欢迎][2]。尽管如此它仍是一门建立在之前所有事物之上的语言。毕竟Rust 不是一天做出来的,所以即便 Rust 中的一些概念看起来与你从 Python、Java、C++ 等编程语言学到的东西大不相同,但它们都是在同一个 CPU 和你一直交互使用(无论你是否知道)的 <ruby>非一致性内存访问<rt>NUMA</rt></ruby> 架构上打下的基础,因此 Rust 中的一些新功能让人感觉有些熟悉。
现在我的职业不是程序员。我没耐心但我又有点儿强迫症。当我需要完成某件事时如果一门语言不能帮助相对较快地获得我想要的结果那么我很少会受到鼓舞而使用它。Rust 试图平衡两个矛盾:现代计算机对安全和结构化代码的需求和现代程序员对编码工作事半功倍的渴望。
### 安装 Rust
[rust-lang.org][3] 网站有丰富的的文档指导如何安装 Rust但通常它就像下载 `sh.rustup.rs` 脚本并运行它一样简单。
```
$ curl --proto '=https' --tlsv1.2 -sSf <https://sh.rustup.rs>
$ less sh.rustup.sh
$ sh ./sh.rustup.rs
```
### 没有类
Rust 没有类,也不使用 `class` 关键字。Rust 确实有 `struct` 数据类型,但它的作用是充当数据集合的一种模板。因此,你可以使用<ruby>结构体<rt>struct</rt></ruby>,而不是创建一个类来表示虚拟对象:
```
struct Penguin {
    genus: String,
    species: String,
    extinct: bool,
    classified: u64,
}
```
你可以像使用类一样使用它。例如,当定义完 `Penguin` 结构,你就可以创建它的实例,并与该实例进行交互:
```
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.");
    }
    
}
```
`impl` 数据类型与 `struct` 数据类型结合使用,你可以实现一个包含函数的结构体,并且可以添加继承和其他与类相似的特性。
### 函数
Rust 中的函数很像其他语言中的函数。每个函数都代表一组严谨的任务,你可以在需要时调用它们。主函数名必须是 `main`
`fn` 关键字声明函数,后跟函数名称和函数接受的所有参数。
```
fn foo() {
  let n = 8;
  println!("Eight is written as {}", n);
}
```
通过参数,将信息从一个函数传递到另一个函数。例如,我已经创建了一个 `Penguin` 类,并且我有一个 `Penguin` 的实例为 `p`,将目标函数的参数指定为 `Penguin`类型,就可把 `p` 的属性从一个函数传递到另一个函数。
```
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.");
  }
}
```
### 变量
Rust 默认创建的为<ruby>不可变<rt>immutable</rt></ruby>变量。这意味着你创建的变量以后无法更改。这段代码虽然看起来没问题,但无法编译:
```
fn main() {
 let n = 6;
 let n = 5;
 }
```
但你可以使用关键字 `mut` 声明一个<ruby>可变<rt>mutable</rt></ruby>变量,因此下面这段代码可以编译成功:
```
fn main() {
 let mut n = 6;
 println!("Value is {}", n);
 n = 5;
 println!("Value is {}", n);
}
```
### 编译
Rust 编译器,至少就其报错信息而言,是可用的最好的编译器之一。当你在 Rust 中出错时,编译器会真诚地告诉你做错了什么。实际上,仅通过从编译器错误消息中学习,我就了解了 Rust 的许多细微差别(就我理解到的 Rust 的任何细微差别而言)。即便有时错误消息太过于模糊,而不知所以然,互联网搜索几乎总能得到解释。
启动 Rust 程序的最简单方法是使用 `cargo`,即 Rust 包管理和构建系统。
```
$ mkdir myproject
$ cd myproject
$ cargo init 
```
以上命令为项目创建了基本的基础架构,最值得注意的是 `src` 子目录中的 `main.rs` 文件。打开此文件,把我为本文生成的示例代码粘贴进去:
```
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);
}
```
使用 `cargo build` 命令进行编译:
```
$ cargo build
```
执行 `target` 子目录下的二进制程序,或者直接运行 `cargo run` 命令来运行你的项目:
```
$ cargo run
Species: R adeliæ
Genus: Pygoscelis
Classified in 1841
Value is 6
Eight is written as 8
```
### Crates
任何语言的大部分便利都来自于它的库或模块。在 Rust 中,进行分发和跟踪的库称为 `crate`。 [crates.io][4] 是一个很好的社区 `crate` 注册网站。
把一个 `crate` 添加到你的 Rust 项目,首先要在 `Cargo.toml` 文件中添加这个 `crate`。 例如,要安装随机数函数,我使用名为 `rand``crate`,使用 `*` 作为通配符,以确保在编译时获得最新版本:
```
[package]
name = "myproject"
version = "0.1.0"
authors = ["Seth &lt;[seth@opensource.com][5]&gt;"]
edition = "2022"
[dependencies]
rand = "*"
```
在 Rust 代码中使用它需要在最顶行使用 `use` 语句:
```
use rand::Rng;
```
以下是一些创建随机种子和随机范围的示例代码:
```
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);
}
```
你可以使用 `cargo run` 来运行它,它会检测代码是否被更改并触发一个新的构建。构建过程中下载名为 `rand``crete` 和它依赖的所有 `crate`,编译代码,然后运行它:
```
$ 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 速查表
Rust 是一门令人非常愉快的语言。它拥有在线注册网站的集成、有用的编译器和几乎直观的语法,给人的感觉非常现代。
但请不要误会Rust 仍是一门复杂的语言它具有严格的数据类型、强作用域变量和许多内置方法。Rust 值得一看,如果你要探索它,那么你应该下载我们的免费 **[Rust 速查表][6]**,以便快速了解基础知识。越早开始,就越早了解 Rust。当然你应该经常练习以避免生疏。
--------------------------------------------------------------------------------
via: https://opensource.com/article/22/1/rust-cheat-sheet
作者:[Seth Kenlon][a]
选题:[lujun9972][b]
译者:[hanszhao80](https://github.com/hanszhao80)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
[a]: https://opensource.com/users/seth
[b]: https://github.com/lujun9972
[1]: https://opensource.com/sites/default/files/styles/image-full-size/public/lead-images/coverimage_cheat_sheet.png?itok=lYkNKieP (Cheat Sheet cover image)
[2]: https://opensource.com/article/20/5/rust-java
[3]: http://rust-lang.org
[4]: https://crates.io/
[5]: mailto:seth@opensource.com
[6]: https://opensource.com/downloads/rust-cheat-sheet