【发布时间】:2021-01-25 12:24:50
【问题描述】:
我有 2 个结构,都实现了一个 trait:
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。我发现 ; 真的很受伤,但现在我明白了:
预期的特征对象
dyn filter::TFilter,找到结构filter::CommentFilter
它不能检测到他们实际实现了这个特征吗?
PS2。我必须明确指定: dyn TFilter,否则编译器会从第一个if 分支推断它并检测为CommentFilter(这显然不适用于负分支)。
【问题讨论】: