Rust 实现多个traits-decorator模式的返回对象
我目前正在Rust中实现装饰图案。 在Scala中,我们可以通过以下特征实现方法链接:Rust 实现多个traits-decorator模式的返回对象,rust,decorator,traits,decltype,Rust,Decorator,Traits,Decltype,我目前正在Rust中实现装饰图案。 在Scala中,我们可以通过以下特征实现方法链接: new Scanner with Whitespaces with Keywords 我想在铁锈上也这样做。因此,扫描仪的不同特点: pub struct Lexer(); pub trait Scan { fn scan(&self, start: &String) -> DomainTags; } pub struct Keywords<T>
new Scanner
with Whitespaces
with Keywords
我想在铁锈上也这样做。因此,扫描仪的不同特点:
pub struct Lexer();
pub trait Scan {
fn scan(&self, start: &String) -> DomainTags;
}
pub struct Keywords<T> {
decorated: T
}
impl<T: Scan> Scan for Keywords<T> {
fn scan(&self, start: &String) -> DomainTags {
...
}
}
pub struct Whitespaces<T> {
decorated: T
}
impl<T: Scan> Scan for Whitespaces<T> {
fn scan(&self, start: &String) -> DomainTags {
...
}
}
我不知道是否可以静态地将返回类型推断为类似decltype(lex)
。实现该方法的常用方法是什么?还有什么可以改进的
为了澄清:我想返回decltype(lex)
,因为我可能也有单个Lexer的多个特征,比如:
pub trait Load {
fn load<T : Load>(&self, keywords: &String);
}
impl Load for Lexer {
fn load<Lexer>(&self, keyword : &String) {
...
}
}
pub属性加载{
fn加载(&self,关键字:&String);
}
Lexer的impl负载{
fn加载(&self,关键字:&String){
...
}
}
我还希望返回一个装饰过的对象,并实现Load-trait。方法加载和扫描都应该可用。函数只能返回一种类型的值,因此函数返回的类型不能依赖于运行时条件。然而,该类型可能是一个装箱的特征,在这种情况下,存储在框中的值的类型可能会改变,只要它实现了适当的特征(或多个特征) 从您提供的示例代码中,我认为
Lexer
应该是一个类似trait Lexer:Scan+Load{}
(或者可能Scan
和Load
特征根本不需要存在,Scan
和Load
方法可以直接在Lexer
中定义)。然后您的构建
函数应该只返回一个装箱的Lexer
:
pub trait Lexer {
fn scan (&self, start: &String) -> DomainTags;
fn load (&self, keyword : &String);
}
pub struct Keywords<T> {
decorated: T
}
impl<T: Lexer> Lexer for Keywords<T> {
…
}
pub struct Whitespaces<T> {
decorated: T
}
impl<T: Lexer> Lexer for Whitespaces<T> {
…
}
pub fn build (cond: bool) -> Box<dyn Lexer> {
if cond {
Box::new (Whitespaces { … })
} else {
Box::new (Keywords { … })
}
}
pub-trait-Lexer{
fn扫描(&self,start:&String)->域标记;
fn加载(&self,关键字:&String);
}
发布结构关键字{
装饰:T
}
关键词导入器{
…
}
pub结构空白{
装饰:T
}
空格的impl Lexer{
…
}
发布fn构建(条件:bool)->Box{
如果条件{
Box::new(空格{…})
}否则{
框::新建(关键字{…})
}
}
因此,根据某些条件,您的函数可能返回Lexer
或关键字
或空白
?然后您需要返回一个框
。是的,您是对的。我编辑了一个问题。如果使用多个特征,它应该是一个盒子还是其他的?
pub trait Lexer {
fn scan (&self, start: &String) -> DomainTags;
fn load (&self, keyword : &String);
}
pub struct Keywords<T> {
decorated: T
}
impl<T: Lexer> Lexer for Keywords<T> {
…
}
pub struct Whitespaces<T> {
decorated: T
}
impl<T: Lexer> Lexer for Whitespaces<T> {
…
}
pub fn build (cond: bool) -> Box<dyn Lexer> {
if cond {
Box::new (Whitespaces { … })
} else {
Box::new (Keywords { … })
}
}