在 Rust 结构体的实现中,*self 在匹配表达式中的所有权是什么?

3

我正在使用此处的示例。

#[derive(Debug)]
enum List {
    Cons(i32, RefCell<Rc<List>>),
    Nil,
}

impl List {
    fn tail(&self) -> Option<&RefCell<Rc<List>>> {
        match *self {
            Cons(_, ref item) => Some(item),
            Nil => None,
        }
    }
}

给定函数签名为&selfself是指向List的引用类型,*selfList实例本身。
但是我记得match也会拥有它匹配的对象,那么这不会对结构体造成问题吗?因为List实例被移动到match而没有返回。
此外,&self不是不可变的吗?为什么我们能将self移动到match中呢?
1个回答

3

match 本身不会移动任何东西。移动、复制或借用发生在 match 的分支中。 示例:

let s = "test".to_string();
let a = s; // this is a move
// println!("{}", s); // ... so this is a "use after move" compilation error

但是如果我们这样做:
match a { // this is allowed, a does not move anywhere
    // but in the branch...
    // this is an error: it would move a to res
    // res if res == "test".to_string() => "ok",
    // ^^^ moves value into pattern guard
    ref res if res == "test" => "ok", // with ref it's fine (we're
    // taking a by reference)
    _ => "ko",
}

游乐场

请注意,您可能会在match中遇到所有权问题,但这通常是由于在match关键字之后执行的某些操作导致的。

例如,以下代码会失败:

// let's break the string in two pieces
match a.split_off(2)
//    ^ cannot borrow mutably

但这是因为需要对&mut self执行split_off,而不是对结果进行match


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接