我剛開始生鏽,但不能完全把握的壽命,所以我可以通過自己解決以下問題:的結構鏽壽命引用
這個測試項目是模擬位以允許通過各種逐位跟蹤它操作,例如let newbit = oldbit1^oldbit2
並在看newbit
我可以告訴它後來它作爲操作數的異或操作與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
參考(即有效至少只要該結構本身和只要構件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 documentation。因此,我試圖以非常明確的方式對兩個輸入變量執行異或運算,並創建一個新的輸入爲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操作本身更長的時間,但我怎麼能解決這個問題?
我已經嘗試了各種解決辦法/更改代碼,但無濟於事,並以任何方式我比較想了解的問題不是猜測正確的解決方案....