I have a Template
struct implementing a encoder
function that returns a reference to a Box
ed Encoder
.
I also have a FixedEncoder
struct that implements Encoder
I can create the Template
and get the Encoder
out, but how do I test the functions of FixedEncoder
? I'm only looking to get FixedEncoder
for testing purposes, so "unsafe" solutions are fine (though safe ones are preferred)
In my following example I get the error
error[E0599]: no method named `length` found for type `&std::boxed::Box<(dyn Encoder + 'static)>` in the current scope
Example (playground):
pub struct Template {
encoder: Box<Encoder>
}
impl Template {
fn new(encoder: Box<Encoder>) -> Template {
Template { encoder }
}
fn encoder(&self) -> &Box<Encoder> {
&self.encoder
}
}
pub trait Encoder {
fn isEncoder(&self) -> bool {
true
}
}
pub struct FixedEncoder {
length: usize
}
impl FixedEncoder {
pub fn new(length: usize) -> FixedEncoder {
FixedEncoder { length }
}
pub fn length(&self) -> usize {
self.length
}
}
impl Encoder for FixedEncoder {}
fn main() {
let fixed_encoder = FixedEncoder::new(1);
let template = Template::new(Box::new(fixed_encoder));
assert_eq!(template.encoder().isEncoder(), true); // works
assert_eq!(&template.encoder().length(), 1); // error[E0599]: no method named `length` found for type `&std::boxed::Box<(dyn Encoder + 'static)>` in the current scope
}