[英]Lifetime parameters for an enum within a struct
我不明白為什么我這種結構會出錯
enum Cell <'a> {
Str(&'a str),
Double(&'a f32),
}
struct MyCellRep<'a> {
value: &'a Cell,
ptr: *const u8,
}
impl MyCellRep{
fn new_from_str(s: &str) {
MyCellRep { value: Cell::Str(&s), ptr: new_sCell(CString::new(&s)) }
}
fn new_from_double(d: &f32) {
MyCellRep { value: Cell::Double(&d), ptr: new_dCell(&d) }
}
}
我收到了錯誤
14:22 error: wrong number of lifetime parameters: expected 1, found 0 [E0107]
src\lib.rs:14 value : & 'a Cell ,
所以我也試過了
struct MyCellRep<'a> {
value: &'a Cell + 'a,
ptr: *const u8,
}
但得到了
14:22 error: expected a path on the left-hand side of `+`, not `&'a Cell`
我假設Cell
應該具有MyCellRep
的生命周期,並且Cell::Str
和Cell::Double
應該至少具有Cell
的生命周期。
最終我能做的就是說
let x = MyCellRef::new_from_str("foo");
let y = MyCellRef::new_from_double(123.0);
更新我想補充一點,通過更改Cell定義,其余的代碼也應該更改為以下搜索答案的其他人。
pub enum Cell<'a> {
Str(&'a str),
Double(&'a f32),
}
struct MyCellRep<'a> {
value: Cell<'a>, // Ref to enum
ptr: *const u8, // Pointer to c struct
}
impl<'a> MyCellRep<'a> {
fn from_str(s: &'a str) -> DbaxCell<'a> {
MyCellRep { value: Cell::Str(&s) , ptr: unsafe { new_sCell(CString::new(s).unwrap()) } }
}
fn from_double(d: &'a f32) -> DbaxCell {
MyCellRep{ value: Cell::Double(&d) , ptr: unsafe { new_dCell(*d) } }
}
}
我對Rust的喜愛就像OCaml一樣,如果它編譯它的工作:)
您(可以理解)誤解了錯誤消息:
14:22 error: wrong number of lifetime parameters: expected 1, found 0 [E0107]
src\lib.rs:14 value : & 'a Cell ,
你想“但我提供了終身參數!它是'a
!' 但是,編譯器試圖告訴您沒有為 Cell提供生命周期參數(不是對它的引用):
Cell<'a>
mdup是正確的 ,但錯誤消息可以幫助您 。 出於某種原因,許多人忽略了指向錯誤的錯誤消息部分:
<anon>:7:16: 7:20 error: wrong number of lifetime parameters: expected 1, found 0 [E0107]
<anon>:7 value: &'a Cell,
^~~~
有時,我想提交一個PR,使^~~~~
在終端^ _ ^中閃爍。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.