我刚开始使用 Rust,但不能完全掌握生命周期,所以我可以自己解决以下问题:
这个测试项目是关于模拟一点,以允许通过各种按位操作对其进行跟踪,例如let newbit = oldbit1 ^ oldbit2
,然后看newbit
我可以告诉它来自一个 XOR 操作,其中oldbit1
和oldbit2
作为操作数。
#[derive(Copy,Clone)]
pub enum TraceOperation {
AND,
OR,
XOR,
NOT,
}
#[derive(Copy,Clone)]
pub struct TraceBit<'a> {
source_a: Option<&'a TraceBit<'a>>,
source_b: Option<&'a TraceBit<'a>>,
source_op: Option<TraceOperation>,
value: bool,
}
这可以编译,但我不完全理解为什么需要这样的生命周期参数。我假设编译器不能期望成员source_a
和source_b
结构本身一样长,因为这可能不成立,因此需要明确的生命周期。
- 这个假设正确吗?
此外,我不完全理解为什么我必须重新指定引用类型的生命周期参数,即为什么我必须写source_a: Option<&'a TraceBit<'a>>
而不是source_a: Option<&'a TraceBit>
.
- 第二个生命周期是用来做什么的?我如何大声读出那句话?我有: "
source_a
是一个类型的变量,Option
它可能具有对"的实例的Some
引用(至少与 struct 本身和 member 一样有效)source_b
TraceBit
我的最后一个问题是我无法使用重载运算符使其工作:
use std::ops::BitXor;
impl<'a> BitXor for TraceBit<'a> {
type Output = Self;
fn bitxor(self, rhs: Self) -> Self {
let valA: usize = if self.value { 1 } else { 0 };
let valB: usize = if rhs.value { 1 } else { 0 };
let val = if valA ^ valB != 0 { true } else { false };
TraceBit { source_a: Some(&self), source_b: Some(&rhs), source_op: Some(TraceOperation::XOR), value: val }
}
}
这基本上是基于BitXor 文档的纯粹猜测。因此,我尝试以非常明确的方式对两个输入变量执行异或运算,并创建一个新TraceBit
的作为输出,并将其中存储的输入作为参考。
error[E0597]: `self` does not live long enough
--> libbittrace/src/lib.rs:37:30
|
37 | TraceBit { source_a: Some(&self), source_b: Some(&rhs), source_op: Some(TraceOperation::XOR), value: val }
| ^^^^ does not live long enough
38 | }
| - borrowed value only lives until here
|
note: borrowed value must be valid for the lifetime 'a as defined on the impl at 31:1...
--> libbittrace/src/lib.rs:31:1
|
31 | / impl<'a> BitXor for TraceBit<'a> {
32 | | type Output = Self;
33 | | fn bitxor(self, rhs: Self) -> Self {
34 | | let valA: usize = if self.value { 1 } else { 0 };
... |
40 | |
41 | | }
| |_^
error[E0597]: `rhs` does not live long enough
--> libbittrace/src/lib.rs:37:53
|
37 | TraceBit { source_a: Some(&self), source_b: Some(&rhs), source_op: Some(TraceOperation::XOR), value: val }
| ^^^ does not live long enough
38 | }
| - borrowed value only lives until here
|
note: borrowed value must be valid for the lifetime 'a as defined on the impl at 31:1...
--> libbittrace/src/lib.rs:31:1
|
31 | / impl<'a> BitXor for TraceBit<'a> {
32 | | type Output = Self;
33 | | fn bitxor(self, rhs: Self) -> Self {
34 | | let valA: usize = if self.value { 1 } else { 0 };
... |
40 | |
41 | | }
| |_^
error: aborting due to 2 previous errors
- 似乎没有什么比 xor 操作本身更长寿,但我该如何解决这个问题?
我已经尝试了各种解决方法/更改代码,但无济于事,无论如何我宁愿理解问题而不是猜测正确的解决方案......