Return a struct that implements a trait

Hello,

I’m extremely naive about rust still and I’ve painted myself into a corner, so any advice on the best approach/fix for this would be welcome. It’s a bit long sorry, but I got some simplified examples

Essentially my problem is I need to return an instance of a struct, but that struct is 1 of 5 possible types, but all will implement a specific trait.

My first attempt worked fine until I added the parse file method with the BufRead parameter, at this point rust complains about the trait cannot be made into an object.

https://play.rust-lang.org/?gist=d3730182d94cae316176a2e009e89f7b&version=stable&mode=debug&edition=2015

After some time on Google, I found I could add a ?Sized in a few places and the new sample looks like this

https://play.rust-lang.org/?gist=f5c4dfe63f73135ae2edf1b2af4d30ac&version=stable&mode=debug&edition=2015

The second attempt compiled and I was happy, until I try and actually use the buf, at that point I get the error the size for values of type R cannot be known at compilation time.

Is what I’m trying to do possible? My only rational for wanting this to accept the buf is so I could potentially write a unit test for it and be able to pass in the buf for the test.

Return a Box<Trait> instead. Alternatively (and probably your best bet) use an enum.

I agree with @gbutler69 that you may want to look into enums since you appear to know all the types a priori. But ...

You can get this to work by changing buf: &R to buf: &mut R because there's a impl<'a, B: BufRead + ?Sized> BufRead for &'a mut B.

If you plan to work only with files, then you can make parse_file non-generic method, which will accept &Path and will handle opening files inside itself.

gbutler69

I thought I was returning a Box, but still had the issues, I did wrap in Option if that made a difference? I’ll look into enum variants however as a better solution, thanks!

vitalyd

That actually does work! However I will also look into the enums, as that seems to be the suggested best approach.

Thanks for your input.