On Fri, Apr 4, 2014 at 10:41 PM, Philippe Delrieu
<[email protected]> wrote:
> Hello,
>
> I've some problem to find a solution for something I want to do with a
> vector of enum. This is an example of what I want to do:
>
> trait Base {
> fn set_something(&mut self);
> }
>
> struct FirstThink;
>
> impl Base for FirstThink {
> fn set_something(&mut self) {}
> }
>
> struct SecondThink;
> impl Base for SecondThink {
> fn set_something(&mut self) {}
> }
>
> enum BaseImpl {
> FirstThinkImpl(~FirstThink),
> SecondThinkImpl(~SecondThink),
> }
>
> fn some_process(list: &mut Vec<&mut ~Base>) {
> for think in list.mut_iter() {
> think.set_something();
> }
> }
>
> struct Container {
> nodeList: Vec<~BaseImpl>,
> }
>
> impl Container {
> fn add_FirstThink(&mut self, think: ~FirstThink) {
> self.nodeList.push(~FirstThinkImpl(think));
> }
> fn add_SecondThink(&mut self, think: ~SecondThink) {
> self.nodeList.push(~SecondThinkImpl(think));
> }
>
> fn do_some_process(&mut self, fct: fn(&mut Vec<&mut ~Base>)) {
> I didn't find a simple way to convert the Vec<~BaseImpl> to a &mut
> Vec<&mut ~Base>
> to do the call
> fct(self.nodeList);
>
> }
> }
>
> I use the enum pattern to have only one collection of object that impl Base
> but sometime I have to do specific processing depending if the Base is a
> FirstThink or SecondThink (not in the example). I use the match as follow
>
> match think {
> FirstThinkImpl(first) => do specific first,
> SecondThinkImpl(second)=> do specific second,
> });
>
> Perhaps there is a better way to do. Any suggestions would be appreciated.
I think that would be better if the `fct` function take an
`std::iter::Iterator<&mut ~Base>` instead of a `Vec`. Naturally, you
will not be able to modify the vector, only to iterate through it. But
if `fct` is allowed to modify the vector your requirements are
impossible in the first place!
Then you can write a simple adaptor:
impl std::iter::Iterator<&mut ~Base> for Container {
// left as an exercise to the reader ;-)
}
--
Rodrigo
_______________________________________________
Rust-dev mailing list
[email protected]
https://mail.mozilla.org/listinfo/rust-dev