How can I test an object's other-trait functions












0















I have a Template struct implementing a encoder function that returns a reference to a Boxed 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
}









share|improve this question




















  • 2





    It isn't possible to "cast" one trait object into another. Probably a more idiomatic approach would be to use an enum of the possible encoders, rather than traits.

    – E4_net_or_something_like_that
    Nov 14 '18 at 20:45






  • 2





    For example: play.rust-lang.org/…

    – E4_net_or_something_like_that
    Nov 14 '18 at 20:55











  • @PeterHall thanks! I'll try integrating and see if it works out. Very much appreciated

    – Aakil Fernandes
    Nov 14 '18 at 21:03






  • 1





    This answer may help to explain why you can't cast between traits - even if you know the type implements them: stackoverflow.com/a/25247480/493729

    – E4_net_or_something_like_that
    Nov 14 '18 at 21:04











  • @PeterHall thanks for the link. I was aware of the inability to cast between traits and sorta understand why (that link certainly helps). I was looking for a workaround an I think the enum solution you provided should work (integrating now).

    – Aakil Fernandes
    Nov 14 '18 at 21:14


















0















I have a Template struct implementing a encoder function that returns a reference to a Boxed 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
}









share|improve this question




















  • 2





    It isn't possible to "cast" one trait object into another. Probably a more idiomatic approach would be to use an enum of the possible encoders, rather than traits.

    – E4_net_or_something_like_that
    Nov 14 '18 at 20:45






  • 2





    For example: play.rust-lang.org/…

    – E4_net_or_something_like_that
    Nov 14 '18 at 20:55











  • @PeterHall thanks! I'll try integrating and see if it works out. Very much appreciated

    – Aakil Fernandes
    Nov 14 '18 at 21:03






  • 1





    This answer may help to explain why you can't cast between traits - even if you know the type implements them: stackoverflow.com/a/25247480/493729

    – E4_net_or_something_like_that
    Nov 14 '18 at 21:04











  • @PeterHall thanks for the link. I was aware of the inability to cast between traits and sorta understand why (that link certainly helps). I was looking for a workaround an I think the enum solution you provided should work (integrating now).

    – Aakil Fernandes
    Nov 14 '18 at 21:14
















0












0








0








I have a Template struct implementing a encoder function that returns a reference to a Boxed 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
}









share|improve this question
















I have a Template struct implementing a encoder function that returns a reference to a Boxed 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
}






rust






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 14 '18 at 21:06









E4_net_or_something_like_that

16.7k74388




16.7k74388










asked Nov 14 '18 at 19:53









Aakil FernandesAakil Fernandes

3,58232040




3,58232040








  • 2





    It isn't possible to "cast" one trait object into another. Probably a more idiomatic approach would be to use an enum of the possible encoders, rather than traits.

    – E4_net_or_something_like_that
    Nov 14 '18 at 20:45






  • 2





    For example: play.rust-lang.org/…

    – E4_net_or_something_like_that
    Nov 14 '18 at 20:55











  • @PeterHall thanks! I'll try integrating and see if it works out. Very much appreciated

    – Aakil Fernandes
    Nov 14 '18 at 21:03






  • 1





    This answer may help to explain why you can't cast between traits - even if you know the type implements them: stackoverflow.com/a/25247480/493729

    – E4_net_or_something_like_that
    Nov 14 '18 at 21:04











  • @PeterHall thanks for the link. I was aware of the inability to cast between traits and sorta understand why (that link certainly helps). I was looking for a workaround an I think the enum solution you provided should work (integrating now).

    – Aakil Fernandes
    Nov 14 '18 at 21:14
















  • 2





    It isn't possible to "cast" one trait object into another. Probably a more idiomatic approach would be to use an enum of the possible encoders, rather than traits.

    – E4_net_or_something_like_that
    Nov 14 '18 at 20:45






  • 2





    For example: play.rust-lang.org/…

    – E4_net_or_something_like_that
    Nov 14 '18 at 20:55











  • @PeterHall thanks! I'll try integrating and see if it works out. Very much appreciated

    – Aakil Fernandes
    Nov 14 '18 at 21:03






  • 1





    This answer may help to explain why you can't cast between traits - even if you know the type implements them: stackoverflow.com/a/25247480/493729

    – E4_net_or_something_like_that
    Nov 14 '18 at 21:04











  • @PeterHall thanks for the link. I was aware of the inability to cast between traits and sorta understand why (that link certainly helps). I was looking for a workaround an I think the enum solution you provided should work (integrating now).

    – Aakil Fernandes
    Nov 14 '18 at 21:14










2




2





It isn't possible to "cast" one trait object into another. Probably a more idiomatic approach would be to use an enum of the possible encoders, rather than traits.

– E4_net_or_something_like_that
Nov 14 '18 at 20:45





It isn't possible to "cast" one trait object into another. Probably a more idiomatic approach would be to use an enum of the possible encoders, rather than traits.

– E4_net_or_something_like_that
Nov 14 '18 at 20:45




2




2





For example: play.rust-lang.org/…

– E4_net_or_something_like_that
Nov 14 '18 at 20:55





For example: play.rust-lang.org/…

– E4_net_or_something_like_that
Nov 14 '18 at 20:55













@PeterHall thanks! I'll try integrating and see if it works out. Very much appreciated

– Aakil Fernandes
Nov 14 '18 at 21:03





@PeterHall thanks! I'll try integrating and see if it works out. Very much appreciated

– Aakil Fernandes
Nov 14 '18 at 21:03




1




1





This answer may help to explain why you can't cast between traits - even if you know the type implements them: stackoverflow.com/a/25247480/493729

– E4_net_or_something_like_that
Nov 14 '18 at 21:04





This answer may help to explain why you can't cast between traits - even if you know the type implements them: stackoverflow.com/a/25247480/493729

– E4_net_or_something_like_that
Nov 14 '18 at 21:04













@PeterHall thanks for the link. I was aware of the inability to cast between traits and sorta understand why (that link certainly helps). I was looking for a workaround an I think the enum solution you provided should work (integrating now).

– Aakil Fernandes
Nov 14 '18 at 21:14







@PeterHall thanks for the link. I was aware of the inability to cast between traits and sorta understand why (that link certainly helps). I was looking for a workaround an I think the enum solution you provided should work (integrating now).

– Aakil Fernandes
Nov 14 '18 at 21:14














1 Answer
1






active

oldest

votes


















0














I was able to accomplish this by using Any.




  1. Add an as_any declaration to Encoder

  2. Add an as_any function to FixedEncoder

  3. Use .as_any().downcast_ref().unwrap() on the retreived Encoder


playground



use std::any::Any;

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
}
fn as_any(&self) -> &dyn Any;
}

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 as_any(&self) -> &dyn Any {
self
}
}

fn main() {
let fixed_encoder = FixedEncoder::new(1);
let template = Template::new(Box::new(fixed_encoder));
assert_eq!(template.encoder().isEncoder(), true); // works

let fixed_encoder_from_template : &FixedEncoder = &template.encoder().as_any().downcast_ref().unwrap();
assert_eq!(&fixed_encoder_from_template.length, &(1 as usize));
}





share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53307834%2fhow-can-i-test-an-objects-other-trait-functions%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    I was able to accomplish this by using Any.




    1. Add an as_any declaration to Encoder

    2. Add an as_any function to FixedEncoder

    3. Use .as_any().downcast_ref().unwrap() on the retreived Encoder


    playground



    use std::any::Any;

    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
    }
    fn as_any(&self) -> &dyn Any;
    }

    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 as_any(&self) -> &dyn Any {
    self
    }
    }

    fn main() {
    let fixed_encoder = FixedEncoder::new(1);
    let template = Template::new(Box::new(fixed_encoder));
    assert_eq!(template.encoder().isEncoder(), true); // works

    let fixed_encoder_from_template : &FixedEncoder = &template.encoder().as_any().downcast_ref().unwrap();
    assert_eq!(&fixed_encoder_from_template.length, &(1 as usize));
    }





    share|improve this answer




























      0














      I was able to accomplish this by using Any.




      1. Add an as_any declaration to Encoder

      2. Add an as_any function to FixedEncoder

      3. Use .as_any().downcast_ref().unwrap() on the retreived Encoder


      playground



      use std::any::Any;

      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
      }
      fn as_any(&self) -> &dyn Any;
      }

      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 as_any(&self) -> &dyn Any {
      self
      }
      }

      fn main() {
      let fixed_encoder = FixedEncoder::new(1);
      let template = Template::new(Box::new(fixed_encoder));
      assert_eq!(template.encoder().isEncoder(), true); // works

      let fixed_encoder_from_template : &FixedEncoder = &template.encoder().as_any().downcast_ref().unwrap();
      assert_eq!(&fixed_encoder_from_template.length, &(1 as usize));
      }





      share|improve this answer


























        0












        0








        0







        I was able to accomplish this by using Any.




        1. Add an as_any declaration to Encoder

        2. Add an as_any function to FixedEncoder

        3. Use .as_any().downcast_ref().unwrap() on the retreived Encoder


        playground



        use std::any::Any;

        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
        }
        fn as_any(&self) -> &dyn Any;
        }

        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 as_any(&self) -> &dyn Any {
        self
        }
        }

        fn main() {
        let fixed_encoder = FixedEncoder::new(1);
        let template = Template::new(Box::new(fixed_encoder));
        assert_eq!(template.encoder().isEncoder(), true); // works

        let fixed_encoder_from_template : &FixedEncoder = &template.encoder().as_any().downcast_ref().unwrap();
        assert_eq!(&fixed_encoder_from_template.length, &(1 as usize));
        }





        share|improve this answer













        I was able to accomplish this by using Any.




        1. Add an as_any declaration to Encoder

        2. Add an as_any function to FixedEncoder

        3. Use .as_any().downcast_ref().unwrap() on the retreived Encoder


        playground



        use std::any::Any;

        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
        }
        fn as_any(&self) -> &dyn Any;
        }

        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 as_any(&self) -> &dyn Any {
        self
        }
        }

        fn main() {
        let fixed_encoder = FixedEncoder::new(1);
        let template = Template::new(Box::new(fixed_encoder));
        assert_eq!(template.encoder().isEncoder(), true); // works

        let fixed_encoder_from_template : &FixedEncoder = &template.encoder().as_any().downcast_ref().unwrap();
        assert_eq!(&fixed_encoder_from_template.length, &(1 as usize));
        }






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 14 '18 at 23:18









        Aakil FernandesAakil Fernandes

        3,58232040




        3,58232040
































            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53307834%2fhow-can-i-test-an-objects-other-trait-functions%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Bressuire

            Vorschmack

            Quarantine