These are chat archives for rust-lang/rust

11th
Oct 2016
Flavius Aspra
@flavius
Oct 11 2016 05:19

Hi. In python I could use metaclasses to get a list of all classes inheriting a base class. Now, I know rust does not have classes, however I'm wondering what would be an idiomatic way to achieve the same effect?

Think about implementing the command pattern: you have different commands, and you want them all to get registered as classes into a generic factory, which can create any command based on an unique id.

The commands would have a common interface.
Johann Tuffe
@tafia
Oct 11 2016 05:31
You're looking for traits
If you want to return the objects either you use an enum (strongly encouraged if you know all the return types) or trait objects (boxed). Perhaps the impl trait might work too
Flavius Aspra
@flavius
Oct 11 2016 05:37
The whole advantage in Python for doing it this way was to make it impossible to forget listing a command "somewhere else", you just had to set the metaclass and the command was automatically registered
Alexander Ronald Altman
@pthariensflame
Oct 11 2016 05:39
You can take advantage of Rust's type system here, actually.
Make a trait that inherits from Default and otherwise implements the interface you want to expose.
Then every individual instance is a unit strict (or something more complicated, if you need to store state) that implements both your trait and Default (which you can derive).
*struct
Alexander Ronald Altman
@pthariensflame
Oct 11 2016 05:42
Yes, that trait.
Flavius Aspra
@flavius
Oct 11 2016 05:42
So where are the commands (the structs) going to be listed?
Alexander Ronald Altman
@pthariensflame
Oct 11 2016 05:42
You can then instantiate your instances polymorphically with Default::new()
Flavius Aspra
@flavius
Oct 11 2016 05:42
Let's say I'd have a "help" command which should list all available commands
Alexander Ronald Altman
@pthariensflame
Oct 11 2016 05:43
Oh.
That sound like a use case for a macro, but you might take a look at how clap accomplishes a similar goal.
Flavius Aspra
@flavius
Oct 11 2016 05:44
I need something like "references to structs", the structs themselves, not instances of them
like Java's .class
(speaking in pragmatic terms)
Alexander Ronald Altman
@pthariensflame
Oct 11 2016 05:46
The underlying latter I was trying to go for was basically defunctionalization as applied manually to OO concepts.
*pattern
If your command list doesn't need to be user-extensible, you can also just use an enum.
Flavius Aspra
@flavius
Oct 11 2016 05:48
it is user-extensible
Alexander Ronald Altman
@pthariensflame
Oct 11 2016 05:49
Then you need to store some kind of static map of keys to defunctionalized structs.
Rust won't give you shared state unless you ask for it explicitly.
Flavius Aspra
@flavius
Oct 11 2016 05:49
interesting stuff @pthariensflame , I'll research more. Thanks
Bradley Weston
@bweston92
Oct 11 2016 07:44
@flavius magic isn't good in most cases