- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
这两个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/
鉴于我使用 matches!宏观 当我尝试将它与枚举一起使用时 然后它显示出意想不到的行为。 请参阅以下最小示例,playground 中也提供了该示例 pub enum Test { FIR
鉴于我使用 matches!宏观 当我尝试将它与枚举一起使用时 然后它显示出意想不到的行为。 请参阅以下最小示例,playground 中也提供了该示例 pub enum Test { FIR
我使用 pcrecpp c++ (PCRE lib) 我需要循环获取所有匹配项。我该怎么做? 例如模式: “你好” 和主题: “你好你好” 循环应该循环 3 次(因为 3 次匹配) 1 你好 2
循环赛算法在每场比赛只有团队相遇时工作正常。但是,如何在超过两支球队在同一场比赛中相遇的体育比赛或比赛中实现它。例如彩弹射击锦标赛,其中 2 到 n 个团队在 2 到 n 场比赛中相遇。仍然保持尽可能
http://ecoocs.org/contests/ecoo_2007.pdf 我正在为我所在地区即将举行的 ecoo regionals 学习,但我对这个问题感到困惑。我真的不知道从哪里开始。 它
如果有人可以帮助我使用二维数组概念而不是使用集合,那就太好了。因为我必须在这个逻辑中使用数组并获取输出。 问题: 第 1 组有四支球队,名称分别为(“A”、“B”、“C”、“D”)第 2 组有四支球队
我几乎正在尝试重新开始 JAVA 编程,只是需要一些我正在从事的小项目的指导。 差不多,我正在举办一场台球锦标赛,我希望每个玩家都能与每个玩家交手一次: 我创建了该程序( https://sconte
我遇到了这个问题,但无法想出解决方案。有一场 Frog 赛跑, Frog 有一定数量的有效跳步。它可以向前或向后移动。为了赢得比赛, Frog 必须尽可能靠近终点线,但不能越过终点线。 例子。6, 1
Closed. This question needs to be more focused。它当前不接受答案。
我正在为篮球赛季创建一个数据库。在这一点上,我保持简单,并存储表: -联盟 id[PK], name->(NBA, NCAAM, etc) -年 id[PK], league_id[FK], year
我将在当前工作的网站上创建竞赛。每个比赛都不会相同,并且可能有不同数量的输入字段,用户必须输入这些字段才能成为比赛的一部分,例如。 比赛 1 可能只需要一个名字 比赛 2 可能需要名字、姓氏和电子邮件
我正在尝试执行一个查询,该查询可以返回 5 个条件中的大多数匹配的结果。但如果只有 5 场比赛中的 5 场比赛,则优先。 为了说明我的问题,已准备好以下 SQL。 declare @tmp table
我已将所有 Json 转换器放在一个文件 JsonUtil 中,然后有一个 ConvertToJson 方法,该方法尝试转换传递给 json 的任何对象。 基本上是这样的结构: implicit va
我是一名优秀的程序员,十分优秀!