How to call a trait function(not method)in generic type struct?

trait Trait {
    fn func();
}

struct StructA {}

impl Trait for StructA {
    fn func() {
        println!("struct a func")
    }
}

struct StructB {}
impl Trait for StructB {
    fn func() {
        println!("struct b func")
    }
}

struct StructC<T: Trait> {
    t: T,
}
impl<T: Trait> StructC<T> {
    fn call_func(&self) {
        self.t::func(); // <-- this code is error, how to make it right
    }
}

fn main() {
    let a = StructC { t: StructA {} };
    a.call_func(); // want print 'struct a func'
    let b = StructC { t: StructB {} };
    b.call_func(); // want print 'struct b func'
}

func has no arguments so it is called using T::func().

Perhaps you meant for func to have a &self argument?

1 Like

no, i just try associated functions.

you need to use types (or its fully qualified path), not variables

// just use type T if there's no ambiguity 
T::func();
// or its fully qualified form
<T as Trait>::func();
2 Likes

bro, you are my hero!