On Sat, Feb 8, 2014 at 6:48 PM, Ashish Myles <[email protected]> wrote:

>
> On Sat, Feb 8, 2014 at 1:21 PM, Philippe Delrieu <[email protected]
> > wrote:
>
>> pub trait Base {
>>     fn do_base(&self);
>> }
>>
>> struct TestBase;
>>
>> impl Base for TestBase    {
>>     fn do_base(&self)    {
>>         println!("ici");
>>     }
>> }
>>
>> trait GenerciFn    {
>>     fn do_generic<T: Base>(&self, base: &T);
>> }
>>
>> struct DoGenericFn;
>>
>> impl GenerciFn for DoGenericFn {
>>     fn do_generic<T: Base>(&self, base: &T)    {
>>         base.do_base();
>>     }
>> }
>>
>> struct ToTestStr    {
>>     vec_gen: ~[~TestBase],
>> }
>>
>> impl ToTestStr    {
>>     fn testgencall<T: GenerciFn>(&self, gen: &T)    {
>>         for base in self.vec_gen.iter()    {
>>             //let test = base as &~TestBase;
>>             gen.do_generic(&**base);
>>         }
>>     }
>> }
>>
>> #[main]
>> fn main() {
>>     let base = TestBase;
>>     let test = ToTestStr {vec_gen: ~[~base],};
>>     let gen = DoGenericFn;
>>     test.testgencall(&gen);
>>
>
>
> It took me a few attempts to get the for loop right, but here you go.
>
>
> pub trait Base {
>     fn do_base(&self);
> }
>
> struct TestBase;
>
> impl Base for TestBase {
>     fn do_base(&self) {
>         println!("ici");
>     }
> }
>
> trait GenericFn {
>     fn do_generic(&self, base: &Base);
> }
>
> struct DoGenericFn;
>
> impl GenericFn for DoGenericFn {
>     fn do_generic(&self, base: &Base) {
>         base.do_base();
>     }
> }
>
> struct ToTestStr {
>     vec_gen: ~[~Base],
> }
>
> impl ToTestStr {
>     fn testgencall<T: GenericFn>(&self, gen: &T)    {
>         for ref base in self.vec_gen.iter() {
>             gen.do_generic(**base);
>         }
>     }
> }
>
> #[main]
> fn main() {
>     let testbase = TestBase;
>     let test = ToTestStr {vec_gen: ~[~testbase as ~Base],};
>
>     let gen = DoGenericFn;
>     test.testgencall(&gen);
> }
>
>
Also, for a little more runtime polymorphism, you could change
testgencall's declaration to
    fn testgencall(&self, gen: &GenericFn) {
    ...
    }
_______________________________________________
Rust-dev mailing list
[email protected]
https://mail.mozilla.org/listinfo/rust-dev

Reply via email to