繁体   English   中英

如何让 static 特征 from_str 方法返回特征?

[英]How to have static trait from_str method return trait?

我对 Rust 仍然很陌生,我试图弄清楚 Java 接口和 Rust 特征之间的差异。 下面的例子是尝试 model 我在 Java 中做事的方式,这可能不是 Rust 中的惯用方式。

我有一个特征,我想通过调用from_str()方法返回特征/接口的一些实现:

pub trait Ast: Display + Debug {
    fn from_str(dot_str: &str) -> Result<Box<Self>, AstParseError>;
    // some other methods applicable to Ast
}

现在这里是 trait 的实现(假设 struct AstParseError存在):

pub struct DotAst {}

impl Ast for DotAst {
    fn from_str(str: &str) -> Result<Box<dyn Ast>, AstParseError> {
        // ...
        // now return a boxed version of my Ast implementation
        Ok(Box::new(DotAst::new()))

    }
}

我收到一个错误“无法将特征Ast制成 object E0038”。 我的 DotAst from_string()实现的签名应该是什么样的? 这在 Rust 中是否可能,或者我应该完全遵循不同的模式。 动机是我想拥有多种类型的 Ast,我想在特定实现上调用from_str()并接收通用 object 回来。

Looks like you just need to append where Self: Sized to the method declaration to make the function "explicitly non-dispatchable": https://doc.rust-lang.org/reference/items/traits.html#object-safety .

pub trait Ast: Debug + Display {
    fn from_str(dot_str: &str) -> Result<Box<dyn Ast>, AstParseError> where Self: Sized;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM