gpt4 book ai didi

struct - 没有从在Rust中实现特征的结构推断出的特征吗?

转载 作者:行者123 更新时间:2023-12-03 11:36:15 27 4
gpt4 key购买 nike

我有2个结构体,都实现了一个特征:

pub trait TFilter {
fn getText(&self) -> String;
}

pub struct CommentFilter {
comment: String
}

impl TFilter for CommentFilter {
fn getText(&self) -> String {
return self.comment;
}
}

impl CommentFilter {
pub fn from_text(context: &Context, text: String) -> Self {
return CommentFilter {
comment: text
}
}
}

// ---

pub struct RegExpFilter {
text: String
}

impl RegExpFilter {
pub fn from_text(context: &Context, text: String) -> Self {
return RegExpFilter {
text
}
}
}

impl TFilter for RegExpFilter {
fn getText(&self) -> String {
return self.text
}
}



但是,当尝试编译代码时:
      let filter: dyn TFilter = if text.chars().nth(0).unwrap() == '!' {
CommentFilter::from_text(context, text);
} else {
RegExpFilter::from_text(context, "test".to_string());
};
我得到一个错误:
error[E0308]: mismatched types
--> src/filter.rs:113:20
|
113 | } else {
| ____________________^
114 | | RegExpFilter::from_text(context, "test".to_string());
115 | | };
| |_____________^ expected trait object `dyn filter::TFilter`, found `()`
怎么了?
PS1。我发现 ;实际上很受伤,但是现在我得到了:

expected trait object dyn filter::TFilter, found struct filter::CommentFilter


它无法检测到他们实际上实现了特质吗?
PS2。我必须明确指定 : dyn TFilter,否则编译器会从第一个 if分支推断出它并检测为 CommentFilter(这显然不适用于否定分支)。

最佳答案

由于编译器不知道TFilter的大小,因此需要将其存储在包装在Box中的堆中,如下所示:

      let filter: Box<dyn TFilter> = if text.chars().nth(0).unwrap() == '!' {
Box::new(CommentFilter::from_text(context, text))
} else {
Box::new(RegExpFilter::from_text(context, "test".to_string()))
};

关于struct - 没有从在Rust中实现特征的结构推断出的特征吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65884753/

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