MOPA: My Own Personal Any. A macro to implement all the
Any methods on your own trait.
Any—its ability to store any
'static type as a trait object and then downcast it
back to the original type is very convenient, and in fact you need it for whatever misguided
reason. But it’s not enough. What you really want is your own trait object type with
functionality glued onto it. Maybe you have a
Person trait and you want your people to be
able to do various things, but you also want to be able to conveniently downcast the person to
its original type, right? Alas, you can’t write a type like
Box<Person + Any> (at present,
anyway). So what do you do instead? Do you give up? No, no! No, no! Enter MOPA.
There once was a quite friendly trait
Person, with much on its plate.
“I need to be
To downcast to
But I’m not, so I guess I’ll just wait.”
A pitiful tale, isn’t it? Especially given that there was a bear chasing it with intent to eat
it. Fortunately now you can mopafy
Person in three simple steps:
mopacrate to your
Cargo.tomlas usual and your crate root like so:
extern crate mopa;
std::any::Any) a supertrait of
And lo, you can now write
person.downcast_ref::<Benny>() and so on
to your heart’s content. Simple, huh?
Oh, by the way, it was actually the person on the bear’s plate. There wasn’t really anything on
Person’s plate after all.
extern crate mopa; mopafy!; ;
Now should you do something like this? Probably not. Enums are probably a better solution for
this particular case as written; frankly I believe that almost the only time you should
downcast an Any trait object (or a mopafied trait object) is with a generic parameter, when
producing something like
AnyMap, for example. If you control all the code,
objects are probably not the right solution; they’re good for cases with user-defined
types across a variety of libraries. But the question of purpose and suitability is open, and I
don’t have a really good example of such a use case here at present. TODO.
Cargo all the way. http://crates.io/crates/mopa
This library is distributed under similar terms to Rust: dual licensed under the MIT license and the Apache license (version 2.0).
See LICENSE-APACHE, LICENSE-MIT, and COPYRIGHT for details.