速成课第6节-练习解答

下面是上一堂 Rust 速成课“生命周期和切片“习题解答。

这篇文章是基于 FP 完成 Rust 教学系列的一部分。 如果你在博客之外阅读这篇文章,你可以在介绍文章的顶部找到这个系列中所有文章的链接。 也可订阅 RSS 频道。

练习1

如果你只是像这样添加 ref 关键字:

match person.age {
    Some(ref age) => {
        println!("Age is {}", age);
        *age += 1;
    }
    None => println!("No age provided"),
}

你会得到一个错误消息:

error[E0594]: cannot assign to immutable borrowed content `*age`
  --> src/main.rs:16:13
   |
14 |         Some(ref age) => {
   |              ------- help: use a mutable reference instead: `ref mut age`
15 |             println!("Age is {}", age);
16 |             *age += 1;
   |             ^^^^^^^^^ cannot borrow as mutable

你需要使用 ref mut age。 如果你像我一样经常输入 mut ref age 而不是 ref mut age。 别担心,编译器会提示你:

error: the order of `mut` and `ref` is incorrect
  --> src/main.rs:14:14
   |
14 |         Some(mut ref age) => {
   |              ^^^^^^^ help: try switching the order: `ref mut`

error: aborting due to previous error

练习2

您需要为要交换的两个参数提供可变引用。 此外,为了获得对 res 的可变引用,res 本身需要是可变的:

fn next(&mut self) -> Option<T> {
    let mut res = None;
    std::mem::swap(&mut res, &mut self.next);
    res
}

练习3

我们需要两个不同的参数,并确保 ret 和返回值具有相同的生存期参数:

fn message_and_return<'a, 'b>(msg: &'a String, ret: &'b String) -> &'b String {
    println!("Printing the message: {}", msg);
    ret
}

练习4

由于数据存储在程序的可执行文件中,因此它在整个程序的执行过程中都是存在的。 因此,生命周期是 'static:

fn main() {
    let bytearray1: &'static [u8; 22] = b"Hello World in binary!";
    let bytearray2: &'static [u8] = b"Hello World in binary!";
    println!("{:?}", bytearray1);
    println!("{:?}", bytearray2);
}

练习5

这是迭代器方法计数的一个很好的用例:

fn main() {
    for arg in std::env::args() {
        println!(
            "arg: {}, characters: {}, bytes: {}",
            arg,
            arg.chars().count(),
            arg.bytes().count(),
            );
    }
}

最后更新于