gpt4 book ai didi

rust - 在比赛中使用ref和与非引用匹配之间是否有区别?

转载 作者:行者123 更新时间:2023-12-03 11:41:42 25 4
gpt4 key购买 nike

这两个match分支是否等效?

struct Quux { wibble: u8 }

enum Foo {
Bar(Quux),
Baz(Quux),
}

impl Foo {
pub fn quux(&self) -> &Quux {
match self {
Foo::Bar(ref quux) => quux,
Foo::Baz(quux) => &quux,
}
}
}
如果是这样,为什么 ref存在?

最佳答案

当我们匹配而不是引用时,它们确实有所不同。考虑以下示例:

enum Foo { 
Bar(i32),
Baz(i32),
}

fn main() {
// bar is a value.
let bar = Foo::Baz(13);

// Uncomment line below to make bar become a reference.
//let bar = &bar;

let i = match bar {
Foo::Bar(ref x) => x,
Foo::Baz(x) => &x,
};
println!("{}", i);
}
编译会出现错误
error[E0597]: `x` does not live long enough
--> src/main.rs:15:24
|
13 | let i = match bar {
| - borrow later stored here
14 | Foo::Bar(ref x) => x,
15 | Foo::Baz(x) => &x,
| ^-
| ||
| |`x` dropped here while still borrowed
| borrowed value does not live long enough
x臂中的 Foo::Baz(x)已获得 i32内部的 Baz的所有权,并被丢弃在臂的末端。这就是 i不能借用 x的原因,因为它生命周期不长。另一方面, x臂中的 Foo::Bar(ref x)没问题,因为它只是借用 i32内的 Bar
但是,如果我们取消注释 let bar = &bar;行,则 bar将成为引用,并且 ref将自动插入每个臂中(根据 rust reference)。这样就可以编译了。
在您的代码中,由于 quux借用了 self( quux(&self))而不是拥有所有权( quux(self)),这意味着 self中的 match self是一个引用,因此可以进行编译。

关于rust - 在比赛中使用ref和与非引用匹配之间是否有区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63628313/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com