ModularM
Modular2y ago
9 replies
Martin Dudek

How to implement Dependency Injection in Mojo?

The following doesnt work (yet) in Mojo it seems
trait Printer:
    fn print_it(self,text:String):
        ...
@value
struct BoringPrinter(Printer):
    fn print_it(self,text:String):
        print(text)

fn lets_print(p:Printer,text:String):
    p.print_it(text)

fn main():
    var bp = BoringPrinter()
    lets_print(bp,"let's sing a song")

i get the following error:
error: invalid call to 'lets_print': argument #0 cannot be converted from 'BoringPrinter' to 'Printer'


Is there a way to implement in Mojo what i am trying to do here. As we don't have inheritence yet i want to use Dependency Injection but without this i feel loooooost.

Any advice on this highly appreciated. Not knowing how to implement this discourages me to think of more interesting framework like Mojo projects unfortunately.
Was this page helpful?