半小时入门 Rust?是的,你没看错

Go语言精选

共 25972字,需浏览 52分钟

 ·

2021-12-09 13:12

对 Rust 稍微了解的朋友,对其学习难度应该有所耳闻。但今天这篇文章,作者试图让新手半小时入门 Rust。你信吗?要不试试?

Rust 是一门系统编程语言,专注于安全:包括内存安全、并发安全等。它支持函数式和命令式以及泛型等多种编程范式。

在这篇文章中,作者并不关注于 1 个或几个关键概念,相反他希望通过代码块纵览 Rust 的各种特性,包括各种关键词与标识符的意义。多读代码,通过代码学习。(螃蟹哥建议:别只是读,动手敲代码更重要)

01 变量

先介绍 let 变量绑定:(注意,Rust 中一般称之为绑定)

let x;  // declare "x"
x = 42// assign 42 to "x"

你也可以写成一行:

let x = 42;

通常,Rust 能够自动推断出变量的类型,但你可以使用 : 来显示指定变量的数据类型:(有时候必须显示指定)

let x: i32// `i32` is a signed 32-bit integer
x = 42;

// there's i8, i16, i32, i64, i128
//    also u8, u16, u32, u64, u128 for unsigned

同样的,你也可以写成一行(一般建议这么写):

let x: i32 = 42;

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

let x;
foobar(x); // error: borrow of possibly-uninitialized variable: `x`
x = 42;

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

let x;
x = 42;
foobar(x); // the type of `x` will be inferred from here

下划线 _ 是一个特殊的变量名,或者更确切地说是「名称的缺失」。它的基本意思是扔掉,可以理解为垃圾桶:(和 Go 中的 _ 差不多)

// this does *nothing* because 42 is a constant
let _ = 42;

// this calls `get_thing` but throws away its result
let _ = get_thing();

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

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

可以引入具有相同名称的另一个绑定——这相当于隐藏前一个变量绑定:

let x = 13;
let x = x + 3;
// using `x` after that line only refers to the second `x`,
// the first `x` no longer exists.

Rust 有元组类型,你可以将其看作是“不同类型值的定长集合”。

let pair = ('a'17);
pair.0// this is 'a'
pair.1// this is 17

如果真的想显示指定 pair 的数据类型,可以这么写:

let pair: (chari32) = ('a'17);

元组在赋值时可以被拆解,也就是它们可以被分解成各自的字段:

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

一个函数可以返还一个元组,这类似于多返回值:

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

当然,在解构一个元组时,可以只分离它的一部分,这就用到了 _

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

分号表示语句的结尾:

let x = 3;
let y = 5;
let z = y + x;

不加分号意味着语句可以跨多行:(这些是什么意思,稍后解释)

let x = vec![12345678]
    .iter()
    .map(|x| x + 3)
    .fold(0, |x, y| x + y);

02 函数

fn 用来声明一个函数。下面是一个 void 函数(没有参数,没有返回值):

fn greet() {
    println!("Hi there!");
}

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

fn fair_dice_roll() -> i32 {
    4
}

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

// This prints "in", then "out"
fn main() {
    let x = "out";
    {
        // this is a different `x`
        let x = "in";
        println!("{}", x);
    }
    println!("{}", x);
}

代码块也是表示式,最后一个表达式的值是整个代码块的值,以下代码表达的意思一样:

// this:
let x = 42;

// is equivalent to this:
let x = { 42 };

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

let x = {
    let y = 1// first statement
    let z = 2// second statement
    y + z // this is the *tail* - what the whole block will evaluate to
};

这也是为什么“省略函数末尾的分号”等同于加上了 retrun,以下是等价的:

fn fair_dice_roll() -> i32 {
    return 4;
}

fn fair_dice_roll() -> i32 {
    4
}

if 条件语句也是表达式:

fn fair_dice_roll() -> i32 {
    if feeling_lucky {
        6
    } else {
        4
    }
}

match 也是一个表达式:

fn fair_dice_roll() -> i32 {
    match feeling_lucky {
        true => 6,
        false => 4,
    }
}

Dots(点号) 通常用于访问某个对象的字段:

let a = (1020);
a.0// this is 10

let amos = get_some_struct();
amos.nickname; // this is "fasterthanlime"

或者调用对象(值)的方法:

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

双冒号(::)与此类似,但它是对命名空间进行操作。

在这个例子中,std 是一个 crate (~ a library),cmp 是一个 module(~ a source file),而 min 是个函数:

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

use 指令可用于从其他命名空间中“引入作用域(scope)”名称:

use std::cmp::min;

let least = min(71); // this is 1

在 use 指令中,花括号还有另一个含义:“globs”。如果我们想同时导入 min 和 max,可以这么做:

// this works:
use std::cmp::min;
use std::cmp::max;

// this also works:
use std::cmp::{min, max};

// this also works!
use std::{cmp::min, cmp::max};

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

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

类型也相当于命名空间,通过 :: 调用其上的方法,以下两种方式等价:

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

str 是基本数据类型(primitive type),但在默认情况下,许多非基本数据类型也在当前作用域中(即不需要手动 use 导入)。

// `Vec` is a regular struct, not a primitive type
let v = Vec::new();

// this is exactly the same code, but with the *full* path to `Vec`
let v = std::vec::Vec::new();

为什么可以这么做呢?为了方便,Rust 在每个模块的开头都插入了以下代码(我认为类似 Java 默认导入 java.lang 包):

use std::prelude::v1::*;

以上代码会以此导出许多标识符,比如 Vec、String、Option、Result。

03 结构体

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

struct Vec2 {
    x: f64// 64-bit floating point, aka "double precision"
    y: f64,
}

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

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

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

let v3 = Vec2 {
    x: 14.0,
    ..v2
};

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

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

let v4 = Vec2 { ..v3 };

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

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

let v = Vec2 { x: 3.0, y: 6.0 };
let Vec2 { x, y } = v;
// `x` is now 3.0, `y` is now `6.0`

还可以这样:

let Vec2 { x, .. } = v;
// this throws away `v.y`

let 模式可以作为 if 的条件使用:

struct Number {
    odd: bool,
    value: i32,
}

fn main() {
    let one = Number { odd: true, value: 1 };
    let two = Number { odd: false, value: 2 };
    print_number(one);
    print_number(two);
}

fn print_number(n: Number) {
    if let Number { odd: true, value } = n {
        println!("Odd number: {}", value);
    } else if let Number { odd: false, value } = n {
        println!("Even number: {}", value);
    }
}

// this prints:
// Odd number: 1
// Even number: 2

多分支的 match 也是一种模式,就像 if let:

fn print_number(n: Number) {
    match n {
        Number { odd: true, value } => println!("Odd number: {}", value),
        Number { odd: false, value } => println!("Even number: {}", value),
    }
}

// this prints the same as before

match 必须是囊括所有情况的的:至少需要匹配一个分支(Rust 中叫做 arm)。

fn print_number(n: Number) {
    match n {
        Number { value: 1, .. } => println!("One"),
        Number { value: 2, .. } => println!("Two"),
        Number { value, .. } => println!("{}", value),
        // if that last arm didn't exist, we would get a compile-time error
    }
}

如果实在没法包含所有情况,可以增加一个 _ 来捕获所有其他情况,类似其他语言 switch 的 default:

fn print_number(n: Number) {
    match n.value {
        1 => println!("One"),
        2 => println!("Two"),
        _ => println!("{}", n.value),
    }
}

你可以在自定义类型上声明方法:

struct Number {
    odd: bool,
    value: i32,
}

impl Number {
    fn is_strictly_positive(self) -> bool {
        self.value > 0
    }
}

然后像平常一样使用:

fn main() {
    let minus_two = Number {
        odd: false,
        value: -2,
    };
    println!("positive? {}", minus_two.is_strictly_positive());
    // this prints "positive? false"
}

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

fn main() {
    let n = Number {
        odd: true,
        value: 17,
    };
    n.odd = false// error: cannot assign to `n.odd`,
                   // as `n` is not declared to be mutable
}

整个结构体值也不能二次赋值:

fn main() {
    let n = Number {
        odd: true,
        value: 17,
    };
    n = Number {
        odd: false,
        value: 22,
    }; // error: cannot assign twice to immutable variable `n`
}

关键字 mut 可以将变量声明变为可变的:

fn main() {
    let mut n = Number {
        odd: true,
        value: 17,
    }
    n.value = 19// all good
}

04 trait(特征)

Traits(特征) 描述的是多种数据类型的共有的东西:(可以类比为其他语言的接口)

trait Signed {
    fn is_strictly_negative(self) -> bool;
}

我们可以这么实现:

  • 可以对外部类型实现自定义的 trait;
  • 可以对自定义类型实现外部 trait;
  • 不允许对外部类型实现外部 trait;

这些被称为“孤儿法则”。你如果有点晕,进一步解释一下:

当你为某类型实现某 trait 的时候,必须要求类型或者 trait 至少有一个是在当前 crate 中定义的。你不能为第三方的类型实现第三方的 trait。

此外,这时记得让 trait 的方法可访问(公开)。

可以在我们上面定义的类型(Number)上实现 trait:

impl Signed for Number {
    fn is_strictly_negative(self) -> bool {
        self.value < 0
    }
}

fn main() {
    let n = Number { odd: false, value: -44 };
    println!("{}", n.is_strictly_negative()); // prints "true"
}

我们对外部类型(foreign type)实现我们定义的 trait:(这里的外部类型使用了基本类型 i32)

impl Signed for i32 {
    fn is_strictly_negative(self) -> bool {
        self < 0
    }
}

fn main() {
    let n: i32 = -44;
    println!("{}", n.is_strictly_negative()); // prints "true"
}

接着在我们定义的类型上实现一个外部 trait:

// the `Neg` trait is used to overload `-`, the
// unary minus operator.
impl std::ops::Neg for Number {
    type Output = Number;

    fn neg(self) -> Number {
        Number {
            value: -self.value,
            odd: self.odd,
        }        
    }
}

fn main() {
    let n = Number { odd: true, value: 987 };
    let m = -n; // this is only possible because we implemented `Neg`
    println!("{}", m.value); // prints "-987"
}

impl 代码块通常会对应一个类型,所以在 impl 内,Self 就表示该类型:

impl std::ops::Neg for Number {
    type Output = Self;

    fn neg(self) -> Self {
        Self {
            value: -self.value,
            odd: self.odd,
        }
    }
}

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

fn main() {
    let a: i32 = 15;
    let b = a; // `a` is copied
    let c = a; // `a` is copied again
}

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

fn print_i32(x: i32) {
    println!("x = {}", x);
}

fn main() {
    let a: i32 = 15;
    print_i32(a); // `a` is copied
    print_i32(a); // `a` is copied again
}

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

fn main() {
    let n = Number { odd: true, value: 51 };
    let m = n; // `n` is moved into `m`
    let o = n; // error: use of moved value: `n`
}

同样下面的代码也不会正常:

fn print_number(n: Number) {
    println!("{} number {}"if n.odd { "odd" } else { "even" }, n.value);
}

fn main() {
    let n = Number { odd: true, value: 51 };
    print_number(n); // `n` is moved
    print_number(n); // error: use of moved value: `n`
}

但如果 print _ number 采用不可变引用,那么它就可以正常工作:

fn print_number(n: &Number) {
    println!("{} number {}"if n.odd { "odd" } else { "even" }, n.value);
}

fn main() {
    let n = Number { odd: true, value: 51 };
    print_number(&n); // `n` is borrowed for the time of the call
    print_number(&n); // `n` is borrowed again
}

如果一个函数接受一个可变的引用,它也可以工作,但前提是我们的变量绑定也是可变的。

fn invert(n: &mut Number) {
    n.value = -n.value;
}

fn print_number(n: &Number) {
    println!("{} number {}"if n.odd { "odd" } else { "even" }, n.value);
}

fn main() {
    // this time, `n` is mutable
    let mut n = Number { odd: true, value: 51 };
    print_number(&n);
    invert(&mut n); // `n is borrowed mutably - everything is explicit
    print_number(&n);
}

trait 方法也可以通过 self 进行引用或可变引用:

impl std::clone::Clone for Number {
    fn clone(&self) -> Self {
        Self { ..*self }
    }
}

当调用 trait 方法时,接收方隐式地被借用:

fn main() {
    let n = Number { odd: true, value: 51 };
    let mut m = n.clone();
    m.value += 100;
    
    print_number(&n);
    print_number(&m);
}

没理解什么意思?以下是等价的,你该理解了:

let m = n.clone();

let m = std::clone::Clone::clone(&n);

像 Copy 这样的标记特征没有方法:

// note: `Copy` requires that `Clone` is implemented too
impl std::clone::Clone for Number {
    fn clone(&self) -> Self {
        Self { ..*self }
    }
}

impl std::marker::Copy for Number {}

现在 Clone 仍然正常:

fn main() {
    let n = Number { odd: true, value: 51 };
    let m = n.clone();
    let o = n.clone();
}

但是 Number 值将不再被移动:

fn main() {
    let n = Number { odd: true, value: 51 };
    let m = n; // `m` is a copy of `n`
    let o = n; // same. `n` is neither moved nor borrowed.
}

有些特性非常常见,它们可以通过 derive 属性自动实现:

#[derive(Clone, Copy)]
struct Number {
    odd: bool,
    value: i32,
}

// this expands to `impl Clone for Number` and `impl Copy for Number` blocks.

05 泛型

函数支持泛型:

fn foobar(arg: T) {
    // do something with `arg`
}

它们可以有多个类型参数,这些参数可以在函数的声明和函数体中使用,而不是具体类型:

fn foobar(left: L, right: R) {
    // do something with `left` and `right`
}

类型参数通常有约束,因此你可以实际使用它们。

最简单的限制是特征(trait)名:

fn print(value: T) {
    println!("value = {}", value);
}

fn printDebug>(value: T) {
    println!("value = {:?}", value);
}

类型参数约束有一个更长的语法:

fn print(value: T)
where
    T: Display,
{
    println!("value = {}", value);
}

约束可能更复杂:它们可能需要一个类型参数来实现多个 traits:

use std::fmt::Debug;

fn compare(left: T, right: T)
where
    T: Debug + PartialEq,
{
    println!("{:?} {} {:?}", left, if left == right { "==" } else { "!=" }, right);
}

fn main() {
    compare("tea""coffee");
    // prints: "tea" != "coffee"
}

泛型函数可以看作是命名空间,包含无数具有不同具体类型的函数。

与 crates、modules 和 类型一样,泛型函数可以通过 :: 指定具体类型:

fn main() {
    use std::any::type_name;
    println!("{}", type_name::<i32>()); // prints "i32"
    println!("{}", type_name::<(f64char)>()); // prints "(f64, char)"
}

这就是所谓的 turbofish 语法,因为 ::<> 看起来像一条鱼。

结构体也可以是泛型:

struct Pair {
    a: T,
    b: T,
}

fn print_type_name(_val: &T) {
    println!("{}", std::any::type_name::());
}

fn main() {
    let p1 = Pair { a: 3, b: 9 };
    let p2 = Pair { a: true, b: false };
    print_type_name(&p1); // prints "Pair"
    print_type_name(&p2); // prints "Pair"
}

标准库类型 Vec(堆分配数组)是泛型的:

fn main() {
    let mut v1 = Vec::new();
    v1.push(1);
    let mut v2 = Vec::new();
    v2.push(false);
    print_type_name(&v1); // prints "Vec"
    print_type_name(&v2); // prints "Vec"
}

06 宏

说到 Vec,它附带了一个宏 “Vec 字面值”。

fn main() {
    let v1 = vec![123];
    let v2 = vec![truefalsetrue];
    print_type_name(&v1); // prints "Vec"
    print_type_name(&v2); // prints "Vec"
}

所有的 name!(),name![] 或 name!{} 都是在调用宏。宏最终会展开为常规代码。

所以,println 也是一个宏。

fn main() {
    println!("{}""Hello there!");
}

这个会展开为和下面有相同效果的代码:

fn main() {
    use std::io::{self, Write};
    io::stdout().lock().write_all(b"Hello there!\n").unwrap();
}

panic 也是一个宏。如果调用了它,会使用错误消息以及错误的文件名/行号强制停止执行:

fn main() {
    panic!("This panics");
}
// output: thread 'main' panicked at 'This panics', src/main.rs:3:5

有些方法也会引起 panic。例如,Option 类型可以包含某些内容,也可以不包含任何内容。如果调用 Unwrap(),但它不包含任何内容,就会 panic:

fn main() {
    let o1: Option<i32> = Some(128);
    o1.unwrap(); // this is fine

    let o2: Option<i32> = None;
    o2.unwrap(); // this panics!
}

// output: thread 'main' panicked at 'called `Option::unwrap()` on a `None` value', src/libcore/option.rs:378:21

07 枚举

Option 不是结构体,而是带有两个变体的枚举:

enum Option {
    None,
    Some(T),
}

impl Option {
    fn unwrap(self) -> T {
        // enums variants can be used in patterns:
        match self {
            Self::Some(t) => t,
            Self::None => panic!(".unwrap() called on a None option"),
        }
    }
}

use self::Option::{NoneSome};

fn main() {
    let o1: Option<i32> = Some(128);
    o1.unwrap(); // this is fine

    let o2: Option<i32> = None;
    o2.unwrap(); // this panics!
}

// output: thread 'main' panicked at '.unwrap() called on a None option', src/main.rs:11:27

Result 也是一个枚举,它可以包含一些东西,或包含一个错误:

enum Result {
    Ok(T),
    Err(E),
}

如果 Result 包含错误时,进行 unwrap 操作会 panic。

08 生命周期

变量绑定有一个“生命周期(lifetime)”:

fn main() {
    // `x` doesn't exist yet
    {
        let x = 42// `x` starts existing
        println!("x = {}", x);
        // `x` stops existing
    }
    // `x` no longer exists
}

类似地,引用也有生命周期:

fn main() {
    // `x` doesn't exist yet
    {
        let x = 42// `x` starts existing
        let x_ref = &x; // `x_ref` starts existing - it borrows `x`
        println!("x_ref = {}", x_ref);
        // `x_ref` stops existing
        // `x` stops existing
    }
    // `x` no longer exists
}

引用的生命周期你不能超过其借用的变量绑定的生命周期:

fn main() {
    let x_ref = {
        let x = 42;
        &x
    };
    println!("x_ref = {}", x_ref);
    // error: `x` does not live long enough
}

一个变量绑定可以被多次借用:

fn main() {
    let x = 42;
    let x_ref1 = &x;
    let x_ref2 = &x;
    let x_ref3 = &x;
    println!("{} {} {}", x_ref1, x_ref2, x_ref3);
}

在被借用期间,变量绑定不能被修改:

fn main() {
    let mut x = 42;
    let x_ref = &x;
    x = 13;
    println!("x_ref = {}", x_ref);
    // error: cannot assign to `x` because it is borrowed
}

当存在不可变借用时,变量不能再次作为可变借用。

fn main() {
    let mut x = 42;
    let x_ref1 = &x;
    let x_ref2 = &mut x;
    // error: cannot borrow `x` as mutable because it is also borrowed as immutable
    println!("x_ref1 = {}", x_ref1);
}

函数参数中的引用也有生命周期:

fn print(x: &i32) {
    // `x` is borrowed (from the outside) for the
    // entire time this function is called.
}

带有引用参数的函数可以使用具有不同生命期的 borrows 来调用,所以:

  • 所有参数是引用的函数,它们实际上都是泛型函数;
  • 生命周期就是泛型参数;

生命周期名以单引号 ' 开头:

// elided (non-named) lifetimes:
fn print(x: &i32) {}

// named lifetimes:
fn print<'a>(x: &'a i32) {}

这允许返回的引用的生命周期依赖于参数的生命周期:

struct Number {
    value: i32,
}

fn number_value<'a>(num: &'a Number) -> &'a i32 {
    &num.value
}

fn main() {
    let n = Number { value: 47 };
    let v = number_value(&n);
    // `v` borrows `n` (immutably), thus: `v` cannot outlive `n`.
    // While `v` exists, `n` cannot be mutably borrowed, mutated, moved, etc.
}

当只有一个输入生命周期时,它不需要命名,所有的东西都具有相同的生命周期,因此下面的两个函数是等价的:

fn number_value<'a>(num: &'a Number) -> &'a i32 {
    &num.value
}

fn number_value(num: &Number) -> &i32 {
    &num.value
}

当有引用字段时,结构体也是基于生命周期的泛型:

struct NumRef<'a> {
    x: &'a i32,
}

fn main() {
    let x: i32 = 99;
    let x_ref = NumRef { x: &x };
    // `x_ref` cannot outlive `x`, etc.
}

同样的代码,但是有一个额外的函数:

struct NumRef<'a> {
    x: &'a i32,
}

fn as_num_ref<'a>(x: &'a i32) -> NumRef<'a> {
    NumRef { x: &x }
}

fn main() {
    let x: i32 = 99;
    let x_ref = as_num_ref(&x);
    // `x_ref` cannot outlive `x`, etc.
}

相同的代码,但省略了生命期:

struct NumRef<'a> {
    x: &'a i32,
}

fn as_num_ref(x: &i32) -> NumRef<'_> {
    NumRef { x: &x }
}

fn main() {
    let x: i32 = 99;
    let x_ref = as_num_ref(&x);
    // `x_ref` cannot outlive `x`, etc.
}

Impl 块也可以是基于生命周期的泛型:

impl<'a> NumRef<'a> {
    fn as_i32_ref(&'a self) -> &'a i32 {
        self.x
    }
}

fn main() {
    let x: i32 = 99;
    let x_num_ref = NumRef { x: &x };
    let x_i32_ref = x_num_ref.as_i32_ref();
    // neither ref can outlive `x`
}

但你也可以在这里省略:

impl<'a> NumRef<'a> {
    fn as_i32_ref(&self) -> &i32 {
        self.x
    }
}

如果你从来不需要这个名字,你可以省去更多:

impl NumRef<'_> {
    fn as_i32_ref(&self) -> &i32 {
        self.x
    }
}

有一个特殊的生命周期,名为 'static,它对整个程序的生命周期都有效。

字符串字面量就是 'static

struct Person {
    name: &'static str,
}

fn main() {
    let p = Person {
        name: "fasterthanlime",
    };
}

但非字面量字符串并不是 static 的:

struct Person {
    name: &'static str,
}

fn main() {
    let name = format!("fasterthan{}""lime");
    let p = Person { name: &name };
    // error: `name` does not live long enough
}

在最后一个示例中,局部变量 name 并不是  &'static str,而是 String。它是动态分配的,并且会在不需要释放。它的生命周期小于整个程序(即使它碰巧在 main 中)。

要在 Person 中存储非 'static 字符串,它需要:

A)基于生命周期的泛型:

struct Person<'a> {
    name: &'a str,
}

fn main() {
    let name = format!("fasterthan{}""lime");
    let p = Person { name: &name };
    // `p` cannot outlive `name`
}

B)取得字符串所有权

struct Person {
    name: String,
}

fn main() {
    let name = format!("fasterthan{}""lime");
    let p = Person { name: name };
    // `name` was moved into `p`, their lifetimes are no longer tied.
}

在 struct literal 中,当一个字段被设置为同名的变量绑定时:

let p = Person { name: name };

它可以这样简写:

let p = Person { name };

09 所有权

对于 Rust 中的许多类型,存在有所有权和没有所有权之分:

  • Strings:String 是有所有权的;$str 是一个引用;
  • Paths:PathBuf 是有所有权的;$Path 是一个引用;
  • Collections:Vec 是有所有权的;&[T] 是一个引用;

Rust 有切片类型(slice)—— 它们是对多个连续元素的引用。

你可以借用 Vector 的一个切片,例如:

fn main() {
    let v = vec![12345];
    let v2 = &v[2..4];
    println!("v2 = {:?}", v2);
}

// output:
// v2 = [3, 4]

以上并不神奇。索引操作符(foo[index])被 Index 和 IndexMut 特征重载。

.. 语法是 range 字面值,range 是标准库中定义的几个结构体。

它们可以是半闭半开的,如果前面有 = ,那么它们就是闭区间。

fn main() {
    // 0 or greater
    println!("{:?}", (0..).contains(&100)); // true
    // strictly less than 20
    println!("{:?}", (..20).contains(&20)); // false
    // 20 or less than 20
    println!("{:?}", (..=20).contains(&20)); // true
    // only 3, 4, 5
    println!("{:?}", (3..6).contains(&4)); // true
}

借用规则适用于切片。

fn tail(s: &[u8]) -> &[u8] {
  &s[1..] 
}

fn main() {
    let x = &[12345];
    let y = tail(x);
    println!("y = {:?}", y);
}

这和下面的一样:

fn tail<'a>(s: &'a [u8]) -> &'a [u8] {
  &s[1..] 
}

以下是合法的:

fn main() {
    let y = {
        let x = &[12345];
        tail(x)
    };
    println!("y = {:?}", y);
}

但因为 [1,2,3,4,5] 是一个 'static 数组。所以,以下是非法的:

fn main() {
    let y = {
        let v = vec![12345];
        tail(&v)
        // error: `v` does not live long enough
    };
    println!("y = {:?}", y);
}

因为 Vector 是在堆分配的,而且它的生命周期是非 'static 的。

&str 实际上是切片。

fn file_ext(name: &str) -> Option<&str> {
    // this does not create a new string - it returns
    // a slice of the argument.
    name.split(".").last()
}

fn main() {
    let name = "Read me. Or don't.txt";
    if let Some(ext) = file_ext(name) {
        println!("file extension: {}", ext);
    } else {
        println!("no file extension");
    }
}

所以,借用规则也适用它:

fn main() {
    let ext = {
        let name = String::from("Read me. Or don't.txt");
        file_ext(&name).unwrap_or("")
        // error: `name` does not live long enough
    };
    println!("extension: {:?}", ext);
}

10 错误处理

可能失败的函数通常返回一个 Result:

fn main() {
    let s = std::str::from_utf8(&[240159141137]);
    println!("{:?}", s);
    // prints: Ok("🍉")

    let s = std::str::from_utf8(&[19540]);
    println!("{:?}", s);
    // prints: Err(Utf8Error { valid_up_to: 0, error_len: Some(1) })
}

如果你想在失败的情况下 panic,你可以调用 unwrap():

fn main() {
    let s = std::str::from_utf8(&[240159141137]).unwrap();
    println!("{:?}", s);
    // prints: "🍉"

    let s = std::str::from_utf8(&[19540]).unwrap();
    // prints: thread 'main' panicked at 'called `Result::unwrap()`
    // on an `Err` value: Utf8Error { valid_up_to: 0, error_len: Some(1) }',
    // src/libcore/result.rs:1165:5
}

或者 .expect(),它可以提供自定义错误信息。

fn main() {
    let s = std::str::from_utf8(&[19540]).expect("valid utf-8");
    // prints: thread 'main' panicked at 'valid utf-8: Utf8Error
    // { valid_up_to: 0, error_len: Some(1) }', src/libcore/result.rs:1165:5
}

或者你也可以使用 match:

fn main() {
    match std::str::from_utf8(&[240159141137]) {
        Ok(s) => println!("{}", s),
        Err(e) => panic!(e),
    }
    // prints 🍉
}

也可以使用 if let:

fn main() {
    if let Ok(s) = std::str::from_utf8(&[240159141137]) {
        println!("{}", s);
    }
    // prints 🍉
}

或者你可以抛出这样的错误:

fn main() -> Result<(), std::str::Utf8Error> {
    match std::str::from_utf8(&[240159141137]) {
        Ok(s) => println!("{}", s),
        Err(e) => return Err(e),
    }
    Ok(())
}

或者你可以使用 ? 来简洁地完成它:

fn main() -> Result<(), std::str::Utf8Error> {
    let s = std::str::from_utf8(&[240159141137])?;
    println!("{}", s);
    Ok(())
}

操作符 * 可用于解引用,但是访问字段或调用方法不需要解引用:

struct Point {
    x: f64,
    y: f64,
}

fn main() {
    let p = Point { x: 1.0, y: 3.0 };
    let p_ref = &p;
    println!("({}, {})", p_ref.x, p_ref.y);
}

// prints `(1, 3)`

而且你只能在类型为 Copy 的情况下才能这么做:

struct Point {
    x: f64,
    y: f64,
}

fn negate(p: Point) -> Point {
    Point {
        x: -p.x,
        y: -p.y,
    }
}

fn main() {
    let p = Point { x: 1.0, y: 3.0 };
    let p_ref = &p;
    negate(*p_ref);
    // error: cannot move out of `*p_ref` which is behind a shared reference
}
// now `Point` is `Copy`
#[derive(Clone, Copy)]
struct Point {
    x: f64,
    y: f64,
}

fn negate(p: Point) -> Point {
    Point {
        x: -p.x,
        y: -p.y,
    }
}

fn main() {
    let p = Point { x: 1.0, y: 3.0 };
    let p_ref = &p;
    negate(*p_ref); // ...and now this works
}

11 闭包

闭包是 Fn、 FnMut 或 FnOnce 类型的函数,包含一些捕获的上下文。

它们的参数是一对管道(|)中以逗号分隔的名称列表。它们不需要大括号,除非您希望有多个语句。

fn for_each_planet(f: F)
    where F: Fn(&'static str)
{
    f("Earth");
    f("Mars");
    f("Jupiter");
}
 
fn main() {
    for_each_planet(|planet| println!("Hello, {}", planet));
}

// prints:
// Hello, Earth
// Hello, Mars
// Hello, Jupiter

借款规则也适用于它们:

fn for_each_planet(f: F)
    where F: Fn(&'static str)
{
    f("Earth");
    f("Mars");
    f("Jupiter");
}
 
fn main() {
    let greeting = String::from("Good to see you");
    for_each_planet(|planet| println!("{}, {}", greeting, planet));
    // our closure borrows `greeting`, so it cannot outlive it
}

例如,这样做不会奏效:

fn for_each_planet(f: F)
    where F: Fn(&'static str) + 'static // `F` must now have "'static" lifetime
{
    f("Earth");
    f("Mars");
    f("Jupiter");
}

fn main() {
    let greeting = String::from("Good to see you");
    for_each_planet(|planet| println!("{}, {}", greeting, planet));
    // error: closure may outlive the current function, but it borrows
    // `greeting`, which is owned by the current function
}

但这样可以:

fn main() {
    let greeting = String::from("You're doing great");
    for_each_planet(move |planet| println!("{}, {}", greeting, planet));
    // `greeting` is no longer borrowed, it is *moved* into
    // the closure.
}

需要可变地借用 FnMut 才能调用它,因此一次只能调用它一次。

这是合法的:

fn foobar(f: F)
    where F: Fn(i32) -> i32
{
    println!("{}", f(f(2))); 
}
 
fn main() {
    foobar(|x| x * 2);
}

// output: 8

但以下不行:

fn foobar(mut f: F)
    where F: FnMut(i32) -> i32
{
    println!("{}", f(f(2))); 
    // error: cannot borrow `f` as mutable more than once at a time
}
 
fn main() {
    foobar(|x| x * 2);
}

不过下面又是合法的:

fn foobar(mut f: F)
    where F: FnMut(i32) -> i32
{
    let tmp = f(2);
    println!("{}", f(tmp)); 
}
 
fn main() {
    foobar(|x| x * 2);
}

// output: 8

FnMut 的存在是因为一些闭包可变地借用了局部变量:

fn foobar(mut f: F)
    where F: FnMut(i32) -> i32
{
    let tmp = f(2);
    println!("{}", f(tmp)); 
}
 
fn main() {
    let mut acc = 2;
    foobar(|x| {
        acc += 1;
        x * acc
    });
}

// output: 24

这些闭包不能传递给期待 Fn 的函数:

fn foobar(f: F)
    where F: Fn(i32) -> i32
{
    println!("{}", f(f(2))); 
}
 
fn main() {
    let mut acc = 2;
    foobar(|x| {
        acc += 1;
        // error: cannot assign to `acc`, as it is a
        // captured variable in a `Fn` closure.
        // the compiler suggests "changing foobar
        // to accept closures that implement `FnMut`"
        x * acc
    });
}

FnOnce 闭包只能调用一次。它们的存在是因为一些闭包移出了捕获时移动的变量:

fn foobar(f: F)
    where F: FnOnce() -> String
{
    println!("{}", f()); 
}
 
fn main() {
    let s = String::from("alright");
    foobar(move || s);
    // `s` was moved into our closure, and our
    // closures moves it to the caller by returning
    // it. Remember that `String` is not `Copy`.
}

这是自然地强制执行的,因为 FnOnce 闭包需要移动才能被调用。

以下例子是无效的:

fn foobar(f: F)
    where F: FnOnce() -> String
{
    println!("{}", f()); 
    println!("{}", f()); 
    // error: use of moved value: `f`
}

而且,如果你需要有说服力的证明我们的关闭确实会发生变化,这也是非法的:

fn main() {
    let s = String::from("alright");
    foobar(move || s);
    foobar(move || s);
    // use of moved value: `s`
}

不过这样是正常的:

fn main() {
    let s = String::from("alright");
    foobar(|| s.clone());
    foobar(|| s.clone());
}

下面是一个包含两个参数的闭包:

fn foobar(x: i32, y: i32, is_greater: F)
    where F: Fn(i32i32) -> bool
{
    let (greater, smaller) = if is_greater(x, y) {
        (x, y)
    } else {
        (y, x)
    };
    println!("{} is greater than {}", greater, smaller);
}
 
fn main() {
    foobar(3264, |x, y| x > y);
}

以下是一个闭包,但忽略了它的两个参数:

fn main() {
    foobar(3264, |_, _| panic!("Comparing is futile!"));
}

下面是一个有点令人担忧的闭包:

fn countdown(count: usize, tick: F)
    where F: Fn(usize)
{
    for i in (1..=count).rev() {
        tick(i);
    }
}
 
fn main() {
    countdown(3, |i| println!("tick {}...", i));
}

// output:
// tick 3...
// tick 2...
// tick 1...

下面是一个 toilet 闭包:

fn main() {
    countdown(3, |_| ());
}

之所以这么叫是因为 |_| () 看起来像个厕所(toilet )。

任何可迭代的东西都可以在 for in 循环中使用。

我们刚刚看到一个 range 被使用,但是它也适用于一个 Vec:

fn main() {
    for i in vec![524921] {
        println!("I like the number {}", i);
    }
}

或者切片:

fn main() {
    for i in &[524921] {
        println!("I like the number {}", i);
    }
}

// output:
// I like the number 52
// I like the number 49
// I like the number 21

或者是迭代器:

fn main() {
    // note: `&str` also has a `.bytes()` iterator.
    // Rust's `char` type is a "Unicode scalar value"
    for c in "rust".chars() {
        println!("Give me a {}", c);
    }
}

// output:
// Give me a r
// Give me a u
// Give me a s
// Give me a t

即使迭代的项目被 filter、map 或 flat:

fn main() {
    for c in "SuRPRISE INbOUND"
        .chars()
        .filter(|c| c.is_lowercase())
        .flat_map(|c| c.to_uppercase())
    {
        print!("{}", c);
    }
    println!();
}

// output: UB

你可以从函数返回一个闭包:

fn make_tester(answer: String) -> impl Fn(&str) -> bool {
    move |challenge| {
        challenge == answer
    }
}

fn main() {
    // you can use `.into()` to perform conversions
    // between various types, here `&'static str` and `String`
    let test = make_tester("hunter2".into());
    println!("{}", test("******"));
    println!("{}", test("hunter2"));
}

你甚至可以将对某个函数参数的引用移动到它返回的闭包中:

fn make_tester<'a>(answer: &'a str) -> impl Fn(&str) -> bool + 'a {
    move |challenge| {
        challenge == answer
    }
}

fn main() {
    let test = make_tester("hunter2");
    println!("{}", test("*******"));
    println!("{}", test("hunter2"));
}

// output:
// false
// true

或者,用省略的生命周期:

fn make_tester(answer: &str) -> impl Fn(&str) -> bool + '_ {
    move |challenge| {
        challenge == answer
    }
}

总结

以上就是这个 30 分钟教程的全部内容。作者认为,通过以上的学习,你应该能够阅读网上找到的大部分 Rust 代码了。

读 Rust 代码和写 Rust 代码很不一样。一方面,你不是读一个问题的解决方案,而是实际解决它;另一方面,Rust 编译器很强大,可以给你很多帮助。

对于这篇教程中故意的错误代码,Rust 编译器总是能非常好的提示你,同时给你很好的建议。

原文链接:https://fasterthanli.me/articles/a-half-hour-to-learn-rust

Rust 编程指北编译,非直接翻译。

实话说,这个教程不可能 30 分钟学完,即使学完了,肯定也没入门。不过通过这些代码,自己动手实践,对学习 Rust 还是有帮助的!



推荐阅读


福利

我为大家整理了一份从入门到进阶的Go学习资料礼包,包含学习建议:入门看什么,进阶看什么。关注公众号 「polarisxu」,回复 ebook 获取;还可以回复「进群」,和数万 Gopher 交流学习。

浏览 43
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报