I started a new project, where I want to be as modular as possible, by that I mean that I would like to be able to replace some parts with others in the future. This seems to be a perfect use for traits
, at the moment I have this code:
mod parser;
mod renderer;
mod renderers;
use parser::MarkParser;
use renderer::MarkRenderer;
struct Rustmark <P: MarkParser, R: MarkRenderer> {
parser: P,
renderer: R,
}
impl <P: MarkParser, R: MarkRenderer> Rustmark <P, R> {
fn new() -> Rustmark <P, R> {
Rustmark {
parser: parser::DefaultParser::new(),
renderer: renderers::HTMLRenderer::new(),
}
}
fn render(&self, input: &str) -> &str {
self.renderer.render(self.parser.parse(input))
}
}
But I get a couple of errors, mainly this one:
error: mismatched types:
expected Rustmark<P, R>
,
found Rustmark<parser::DefaultParser, renderers::html::HTMLRenderer>
(expected type parameter,
found struct parser::DefaultParser
) [E0308]
And a couple of lifetime errors like this one:
error: cannot infer an appropriate lifetime for automatic coercion due to conflicting requirements
help: consider using an explicit lifetime parameter as shown: fn parse<'a>(&'a self, input: &'a str) -> &str
I have tried multiple tweaks to make it work, but none of them seemed to appease the compiler. So I wanted to know if this is the right approach and what I could do to to make it work.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…