📔
rust-crash-course-zh
  • 目录
  • 0. Rust速成课介绍
  • 1. 小试牛刀
    • 速成课第1节
    • 速成课第1节-练习解答
  • 2. 所有权基础
    • 速成课第2节
    • 速成课第2节-练习解答
  • 3. 迭代器与错误
    • 速成课第3节
    • 速成课第3节-练习解答
  • 4. Crates和更多的迭代器
    • 速成课第4节
    • 速成课第4节-练习解答
  • 5. 参数、迭代器和闭包三法则
    • 速成课第5节
    • 速成课第5节-练习解答
  • 6. 生命周期和切片
    • 速成课第6节
    • 速成课第6节-练习解答
  • 7. Async,Futures和Tokio
  • 8. 直接了当的Future
  • 9. Tokio 0.2
由 GitBook 提供支持
在本页
  • 练习1
  • 练习2
  • 练习3
  • 练习4
  • 练习5

这有帮助吗?

  1. 6. 生命周期和切片

速成课第6节-练习解答

上一页速成课第6节下一页7. Async,Futures和Tokio

最后更新于4年前

这有帮助吗?

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

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

练习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(),
            );
    }
}
FP
介绍文章的顶部
订阅 RSS