半小时入门Rust,这是一篇Rust代码风暴

新闻 前端
据说很多开发者一天入门 Python,两天上手 Go,但到了 Rust 就会发现画风隐约有些不对。它从语法到特性,似乎都要复杂一些。本文介绍的就是 Rust,作者表示,通过解析大量代码,「半个小时」就能入门 Rust。

据说很多开发者一天入门 Python,两天上手 Go,但到了 Rust 就会发现画风隐约有些不对。它从语法到特性,似乎都要复杂一些。本文介绍的就是 Rust,作者表示,通过解析大量代码,「半个小时」就能入门 Rust。

[[318599]]

Rust 是一门系统编程语言,专注于安全,尤其是并发安全。它支持函数式和命令式以及泛型等编程范式的多范式语言,且 TensorFlow 等深度学习框架也把它作为一个优秀的前端语言。

Rust 在语法上和 C、C++类似,都由花括弧限定代码块,并有相同的控制流关键字,但 Rust 设计者想要在保证性能的同时提供更好的内存安全。Rust 自 2016 年就已经开源了,在各种开发者调查中,它也总能获得「最受欢迎的语言」这一称赞,目前该开源项目已有 42.9K 的 Star 量。

机器之心的读者大多数都非常熟悉 Python,而 Rust 就没那么熟悉了。在 Amos 最近的一篇博文中,他表示如果阅读他的作品,我们半个小时就能入门 Rust。因此在这篇文章中,我们将介绍该博文的主要内容,它并不关注于 1 个或几个关键概念,相反它希望通过代码块纵览 Rust 的各种特性,包括各种关键词与符号的意义。

在 HackNews 上,很多开发者表示这一份入门教程非常实用,Rust 的入门门槛本来就比较高,如果再介绍各种复杂的概念与特性,很容易出现「从入门到劝退」。因此这种从实例代码出发的教程,非常有意义。

从变量说起

let 能绑定变量:

  1. let x; // declare "x" 
  2.  
  3. x = 42// assign 42 to "x" 
  4.  
  5. let x = 42// combined in one line 

可以使用 :来制定变量的数据类型,以及数据类型注释:

  1. let x: i32; // `i32` is a signed 32-bit integer 
  2.  
  3. x = 42
  4.  
  5. // there's i8, i16, i32, i64, i128 
  6.  
  7. // also u8, u16, u32, u64, u128 for unsigned 
  8.  
  9. let x: i32 = 42// combined in one line 

如果你声明一个变量并在初始化之前就调用它,编译器会报错:

  1. let x; 
  2.  
  3. foobar(x); // error: borrow of possibly-uninitialized variable: `x` 
  4.  
  5. x = 42

然而,这样做完全没问题:

  1. let x; 
  2.  
  3. x = 42
  4.  
  5. foobar(x); // the type of `x` will be inferred from here 

下划线表示特殊的命名,或者更确切地说是「缺失的命名」,它和 Python 的用法有点像:

  1. // this does *nothing* because 42 is a constant 
  2.  
  3. let _ = 42
  4.  
  5. // this calls `get_thing` but throws away its result 
  6.  
  7. let _ = get_thing(); 

以下划线开头的命名是常规命名,只是编译器不会警告它们未被使用:

  1. // we may use `_x` eventually, but our code is a work-in-progress 
  2.  
  3. // and we just wanted to get rid of a compiler warning for now. 
  4.  
  5. let _x = 42

相同命名的单独绑定是可行的,第一次绑定的变量会取消:

  1. let x = 13
  2.  
  3. let x = x + 3
  4.  
  5. // using `x` after that line only refers to the second `x`, 
  6.  
  7. // the first `x` no longer exists. 

Rust 有元组类型,可以将其看作是「不同数据类型值的定长集合」。

  1. let pair = ('a'17); 
  2.  
  3. pair.0// this is 'a' 
  4.  
  5. pair.1// this is 17 

如果真的想配置 pair 的数据类型,可以这么写:

  1. let pair: (char, i32) = ('a'17); 

元组在赋值时可以被拆解,这意味着它们被分解成各个字段:

  1. let (some_char, some_int) = ('a'17); 
  2.  
  3. // now, `some_char` is 'a', and `some_int` is 17 

当一个函数返还一个元组时会非常有用:

  1. let (left, right) = slice.split_at(middle); 

当然,在解构一个元组时,可以只分离它的一部分:

  1. let (_, right) = slice.split_at(middle); 

分号表示语句的结尾:

  1. let x = 3
  2.  
  3. let y = 5
  4.  
  5. let z = y + x; 

不加分号意味着语句可以跨多行:

  1. let x = vec![12345678
  2.  
  3. .iter() 
  4.  
  5. .map(|x| x + 3
  6.  
  7. .fold(0, |x, y| x + y); 

函数来了

fn 声明一个函数。下面是一个空函数:

  1. fn greet() { 
  2.  
  3. println!("Hi there!"); 
  4.  

这是一个返还 32 位带符号整数值的函数。箭头表示返还类型:

  1. fn fair_dice_roll() -> i32 { 
  2.  
  3. 4 
  4.  

花括号表示了一个代码块,且拥有其自己的作用域:

  1. // This prints "in", then "out" 
  2.  
  3. fn main() { 
  4.  
  5. let x = "out"
  6.  
  7.  
  8. // this is a different `x` 
  9.  
  10. let x = "in"
  11.  
  12. println!(x); 
  13.  
  14.  
  15. println!(x); 
  16.  

代码块也是表示式,表示其计算为一个值。

  1. // this: 
  2.  
  3. let x = 42
  4.  
  5. // is equivalent to this: 
  6.  
  7. let x = { 42 }; 

在一个代码块中,可以有多个语句:

  1. let x = { 
  2.  
  3. let y = 1// first statement 
  4.  
  5. let z = 2// second statement 
  6.  
  7. y + z // this is the *tail* - what the whole block will evaluate to 
  8.  
  9. }; 

这也是为什么「省略函数末尾的分号」等同于加上了 Retrun,这些都是等价的:

  1. fn fair_dice_roll() -> i32 { 
  2.  
  3. return 4
  4.  
  5.  
  6. fn fair_dice_roll() -> i32 { 
  7.  
  8. 4 
  9.  

if 条件语句也是表达式:

  1. fn fair_dice_roll() -> i32 { 
  2.  
  3. if feeling_lucky { 
  4.  
  5. 6 
  6.  
  7. else { 
  8.  
  9. 4 
  10.  
  11.  

match 匹配器也是一个表达式:

  1. fn fair_dice_roll() -> i32 { 
  2.  
  3. match feeling_lucky { 
  4.  
  5. true => 6
  6.  
  7. false => 4
  8.  
  9.  

Dots 通常用于访问某个对象的字段:

  1. let a = (1020); 
  2.  
  3. a.0// this is 10 
  4.  
  5. let amos = get_some_struct(); 
  6.  
  7. amos.nickname; // this is "fasterthanlime" 

或者调用对象的方法:

  1. let nick = "fasterthanlime"
  2.  
  3. nick.len(); // this is 14 

双冒号与此类似,但可对命名空间进行操作。在此举例中,std 是一个 crate (~ a library),cmp 是一个 module(~ a source file),以及 min 是个函数:

  1. let least = std::cmp::min(38); // this is 3 

use 指令可用于从其他命名空间中「引入范围」命名:

  1. use std::cmp::min; 
  2.  
  3. let least = min(71); // this is 1 

在 use 指令中,花括号还有另一个含义:「globs」,因此可以同时导入 min 以及 max:

  1. // this works: 
  2.  
  3. use std::cmp::min; 
  4.  
  5. use std::cmp::max; 
  6.  
  7. // this also works: 
  8.  
  9. use std::cmp::{min, max}; 
  10.  
  11. // this also works! 
  12.  
  13. use std::{cmp::min, cmp::max}; 

通配符(*)允许从命名空间导入符号:

  1. // this brings `min` and `max` in scope, and many other things 
  2.  
  3. use std::cmp::*; 

Types 也是命名空间和方法,它可以作为常规函数调用:

  1. let x = "amos".len(); // this is 4 
  2.  
  3. let x = str::len("amos"); // this is also 4 

str 是一个基元数据类型,但在默认情况下,许多非基元数据类型也在作用域中。

  1. // `Vec` is a regular struct, not a primitive type 
  2.  
  3. let v = Vec::new(); 
  4.  
  5. // this is exactly the same code, but with the *full* path to `Vec` 
  6.  
  7. let v = std::vec::Vec::new() 

至于为什么可行,因为 Rust 在每个模块的开头都插入了:

  1. use std::prelude::v1::*; 

再说说结构体

使用 struct 关键字声明结构体:

  1. struct Vec2 { 
  2.  
  3. x: f64, // 64-bit floating point, aka "double precision" 
  4.  
  5. y: f64, 
  6.  

可以使用结构语句初始化:

  1. let v1 = Vec2 { x: 1.0, y: 3.0 }; 
  2.  
  3. let v2 = Vec2 { y: 2.0, x: 4.0 }; 
  4.  
  5. // the order does not matter, only the names do 

有一个快捷方式可以从另一个结构体初始化本结构体的其余字段:

  1. let v3 = Vec2 { 
  2.  
  3. x: 14.0
  4.  
  5. ..v2 
  6.  
  7. }; 

这就是所谓的「结构体更新语法」只能发生在最后一个位置,不能在其后面再跟一个逗号。

注意其余字段可以表示所有字段:

  1. let v4 = Vec2 { ..v3 }; 

结构体与元组一样,可以被解构。例如一个有效的 let 模式:

  1. let (left, right) = slice.split_at(middle); 
  2.  
  3. let v = Vec2 { x: 3.0, y: 6.0 }; 
  4.  
  5. let Vec2 { x, y } = v; 
  6.  
  7. // `x` is now 3.0, `y` is now `6.0` 
  8.  
  9. let Vec2 { x, .. } = v; 
  10.  
  11. // this throws away `v.y` 

让 let 模式在 if 里可以作为条件:

  1. struct Number { 
  2.  
  3. odd: bool, 
  4.  
  5. value: i32, 
  6.  
  7.  
  8. fn main() { 
  9.  
  10. let one = Number { odd: true, value: 1 }; 
  11.  
  12. let two = Number { odd: false, value: 2 }; 
  13.  
  14. print_number(one); 
  15.  
  16. print_number(two); 
  17.  
  18.  
  19. fn print_number(n: Number) { 
  20.  
  21. if let Number { odd: true, value } = n { 
  22.  
  23. println!("Odd number: {}", value); 
  24.  
  25. else if let Number { odd: false, value } = n { 
  26.  
  27. println!("Even number: {}", value); 
  28.  
  29.  
  30.  
  31. // this prints: 
  32.  
  33. // Odd number: 1 
  34.  
  35. // Even number: 2 

多分支的 match 也是条件模式,就像 if let:

  1. fn print_number(n: Number) { 
  2.  
  3. match n { 
  4.  
  5. Number { odd: true, value } => println!("Odd number: {}", value), 
  6.  
  7. Number { odd: false, value } => println!("Even number: {}", value), 
  8.  
  9.  
  10.  
  11. // this prints the same as before 

match 必须是囊括所有情况的的:至少需要匹配一个条件分支。

  1. fn print_number(n: Number) { 
  2.  
  3. match n { 
  4.  
  5. Number { value: 1, .. } => println!("One"), 
  6.  
  7. Number { value: 2, .. } => println!("Two"), 
  8.  
  9. Number { value, .. } => println!("{}", value), 
  10.  
  11. // if that last arm didn't exist, we would get a compile-time error 
  12.  
  13.  

如果非常难实现,_ 那么可以作用一个“包罗万象”的模式:

  1. fn print_number(n: Number) { 
  2.  
  3. match n.value { 
  4.  
  5. 1 => println!("One"), 
  6.  
  7. 2 => println!("Two"), 
  8.  
  9. _ => println!("{}", n.value), 
  10.  
  11.  

Type 别名

我们可以使用 type 关键字声明另一类型的别名,然后就可以像使用一个真正的类型一样使用这种类型。例如定义 Name 这种数据类型为字符串,后面就可以直接使用 Name 这种类型了。

你可以在方法中声明不同的数据类型:

  1. struct Number { 
  2.  
  3. odd: bool, 
  4.  
  5. value: i32, 
  6.  
  7.  
  8. impl Number { 
  9.  
  10. fn is_strictly_positive(self) -> bool { 
  11.  
  12. self.value > 0 
  13.  
  14.  

然后就如同往常那样使用:

  1. fn main() { 
  2.  
  3. let minus_two = Number { 
  4.  
  5. odd: false
  6.  
  7. value: -2
  8.  
  9. }; 
  10.  
  11. println!("positive? {}", minus_two.is_strictly_positive()); 
  12.  
  13. // this prints "positive? false" 
  14.  

默认情况下,声明变量后它就就是不可变的,如下 odd 不能被重新赋值:

  1. fn main() { 
  2.  
  3. let n = Number { 
  4.  
  5. odd: true
  6.  
  7. value: 17
  8.  
  9. }; 
  10.  
  11. n.odd = false// error: cannot assign to `n.odd`, 
  12.  
  13. // as `n` is not declared to be mutable 
  14.  

不可变的变量声明,其内部也是不可变的,它也不能重新分配值:

  1. fn main() { 
  2.  
  3. let n = Number { 
  4.  
  5. odd: true
  6.  
  7. value: 17
  8.  
  9. }; 
  10.  
  11. n = Number { 
  12.  
  13. odd: false
  14.  
  15. value: 22
  16.  
  17. }; // error: cannot assign twice to immutable variable `n` 
  18.  

mut 可以使变量声明变为可变的:

  1. fn main() { 
  2.  
  3. let mut n = Number { 
  4.  
  5. odd: true
  6.  
  7. value: 17
  8.  
  9.  
  10. n.value = 19// all good 
  11.  

Traits 描述的是多种数据类型的共同点:

  1. trait Signed { 
  2.  
  3. fn is_strictly_negative(self) -> bool; 
  4.  

我们可以在我们定义的 Type 类型中定义 Traits:

  1. impl Signed for Number { 
  2.  
  3. fn is_strictly_negative(self) -> bool { 
  4.  
  5. self.value < 0 
  6.  
  7.  
  8.  
  9. fn main() { 
  10.  
  11. let n = Number { odd: false, value: -44 }; 
  12.  
  13. println!("{}", n.is_strictly_negative()); // prints "true" 
  14.  

外部类型(foreign type)中定义的 Trait:

  1. impl Signed for i32 { 
  2.  
  3. fn is_strictly_negative(self) -> bool { 
  4.  
  5. self < 0 
  6.  
  7.  
  8.  
  9. fn main() { 
  10.  
  11. let n: i32 = -44
  12.  
  13. println!("{}", n.is_strictly_negative()); // prints "true" 
  14.  

impl 模块通常会带有一个 Type 类型,所以在模块内,Self 就表示该类型:

  1. impl std::ops::Neg for Number { 
  2.  
  3. type Output = Self; 
  4.  
  5. fn neg(self) -> Self { 
  6.  
  7. Self { 
  8.  
  9. value: -self.value, 
  10.  
  11. odd: self.odd, 
  12.  
  13.  
  14.  

有一些traits只是作为标记,它们并不是说 Type 类型实现了某些方法,它只是表明某些东西能通过Type类型完成。例如,i32 实现了Copy,那么以下代码就是可行的:

  1. fn main() { 
  2.  
  3. let a: i32 = 15
  4.  
  5. let b = a; // `a` is copied 
  6.  
  7. let c = a; // `a` is copied again 
  8.  

下面的代码也是能运行的:

  1. fn print_i32(x: i32) { 
  2.  
  3. println!("x = {}", x); 
  4.  
  5.  
  6. fn main() { 
  7.  
  8. let a: i32 = 15
  9.  
  10. print_i32(a); // `a` is copied 
  11.  
  12. print_i32(a); // `a` is copied again 
  13.  

但是 Number 的结构体并不能用于 Copy,所以下面的代码会报错:

  1. fn main() { 
  2.  
  3. let n = Number { odd: true, value: 51 }; 
  4.  
  5. let m = n; // `n` is moved into `m` 
  6.  
  7. let o = n; // error: use of moved value: `n` 
  8.  

同样下面的代码也不会 Work:

  1. fn print_number(n: Number) { 
  2.  
  3. println!("{} number {}"if n.odd { "odd" } else { "even" }, n.value); 
  4.  
  5.  
  6. fn main() { 
  7.  
  8. let n = Number { odd: true, value: 51 }; 
  9.  
  10. print_number(n); // `n` is moved 
  11.  
  12. print_number(n); // error: use of moved value: `n` 
  13.  

但是如果print_number有一个不可变reference,那么 Copy 就是可行的:

  1. fn print_number(n: &Number) { 
  2.  
  3. println!("{} number {}"if n.odd { "odd" } else { "even" }, n.value); 
  4.  
  5.  
  6. fn main() { 
  7.  
  8. let n = Number { odd: true, value: 51 }; 
  9.  
  10. print_number(&n); // `n` is borrowed for the time of the call 
  11.  
  12. print_number(&n); // `n` is borrowed again 
  13.  

如果函数采用了可变reference,那也是可行的,只不过需要在变量声明中带上 mut。

  1. fn invert(n: &mut Number) { 
  2.  
  3. n.value = -n.value; 
  4.  
  5.  
  6. fn print_number(n: &Number) { 
  7.  
  8. println!("{} number {}"if n.odd { "odd" } else { "even" }, n.value); 
  9.  
  10.  
  11. fn main() { 
  12.  
  13. // this time, `n` is mutable 
  14.  
  15. let mut n = Number { odd: true, value: 51 }; 
  16.  
  17. print_number(&n); 
  18.  
  19. invert(&mut n); // `n is borrowed mutably - everything is explicit 
  20.  
  21. print_number(&n); 
  22.  

Copy 这类标记型的traits并不带有方法:

  1. // note: `Copy` requires that `Clone` is implemented too 
  2.  
  3. impl std::clone::Clone for Number { 
  4.  
  5. fn clone(&self) -> Self { 
  6.  
  7. Self { ..*self } 
  8.  
  9.  
  10.  
  11. impl std::marker::Copy for Number {} 

现在 Clone 仍然可以用于:

  1. fn main() { 
  2.  
  3. let n = Number { odd: true, value: 51 }; 
  4.  
  5. let m = n.clone(); 
  6.  
  7. let o = n.clone(); 
  8.  

但是Number的值将不会再移除:

  1. fn main() { 
  2.  
  3. let n = Number { odd: true, value: 51 }; 
  4.  
  5. let m = n; // `m` is a copy of `n` 
  6.  
  7. let o = n; // same. `n` is neither moved nor borrowed. 
  8.  

有一些traits很常见,它们可以通过使用derive 属性自动实现:

  1. #[derive(Clone, Copy)] 
  2.  
  3. struct Number { 
  4.  
  5. odd: bool, 
  6.  
  7. value: i32, 
  8.  
  9.  
  10. // this expands to `impl Clone for Number` and `impl Copy for Number` blocks. 

看上去,整篇教程都在使用大量代码解释 Rust 的各种语句与用法。可能我们会感觉博客结构不是太明确,但是实例驱动的代码学习确实更加高效。尤其是对于那些有一些编程基础的同学,他们可以快速抓住 Rust 语言的特点与逻辑。

最后,这篇文章并没有展示博客所有的内容,如果读者想真正入门 Rust 语言,推荐可以查阅原博客。

 

 

责任编辑:张燕妮 来源: 机器之心
相关推荐

2023-11-28 08:29:31

Rust内存布局

2022-03-10 16:51:46

C语言代码if语句

2022-05-08 16:42:27

Rust编程语言

2019-10-22 18:00:00

MySQL基础入门数据库

2023-09-21 11:39:29

RustJetBrainsIDE

2023-06-19 14:14:24

Rust程序Web

2019-12-13 16:19:15

戴尔

2020-09-25 08:10:55

Rust系统编程

2024-04-11 13:13:27

2023-04-20 08:00:00

ES搜索引擎MySQL

2020-03-09 11:43:35

RustCargo编程语言

2022-07-25 11:10:58

Rust教程编程语言

2024-04-22 08:06:34

Rust语言

2023-05-29 16:25:59

Rust函数

2020-09-01 07:50:21

Rust 编程语言

2021-02-24 07:42:34

PythonRust语言

2023-06-15 17:00:11

Rust循环

2022-07-06 07:57:37

Zookeeper分布式服务框架

2022-02-21 09:44:45

Git开源分布式

2021-01-28 08:55:48

Elasticsear数据库数据存储
点赞
收藏

51CTO技术栈公众号