小编luc*_*ler的帖子

在“if let Some(ref mut x) = option”和“if let Some(x) = option.as_mut()”中匹配可变选项引用有什么区别?

背景

考虑一个玩具问题,其中我有一个Node表示链表节点的结构,并且我想创建一个函数来构建一个值从 1 到 9 的列表。以下代码按预期工作:

struct Node {
    val: i32,
    next: Option<Box<Node>>,
}

fn build_list() -> Option<Box<Node>> {
    let mut head = None;
    let mut tail = &mut head;
    for n in 1..10 {
        *tail = Some(Box::new(Node {val: n, next: None}));
        if let Some(ref mut x) = tail {
            tail = &mut x.next;
        };
    }
    head
}
Run Code Online (Sandbox Code Playgroud)

但是,如果我将build_list函数中的匹配表达式修改为以下内容,则无法编译:

fn build_list() -> Option<Box<Node>> {
    let mut head = None;
    let mut tail = &mut head;
    for …
Run Code Online (Sandbox Code Playgroud)

reference mutable rust

10
推荐指数
1
解决办法
559
查看次数

标签 统计

mutable ×1

reference ×1

rust ×1