TraitsRequiring Static Methods
What am I doing wrong below? please help.
trait HasStaticMethod:
@staticmethod
fn work(): ...
@value
struct WashingMachine:
@staticmethod
fn work():
print("Wash the clothes!")
@value
struct Cooker:
@staticmethod
fn work():
print("Cook the food!")
fn main():
fn do_workT: HasStaticMethod:
T.work()
do_work(WashingMachine())
9 Replies
What error do you get?
You have to put trait conformance in struct declarations.
Oh that’s right, the structs aren’t inheriting the trait.
Try
struct WashingMachine(HasStaticMethod):
Thanks, will try it.
Does anyone know whether implicit trait implementation has been considered? Nominal vs structural sort-of-thing.
I don’t know. The language is generally quite verbose.
yes implicit traits conformance is in the works, see the latest newsletter
Thank you!
“The Mojo team is considering implicit conformance for traits. For example, you'll be able to just implement str() on a struct to make it printable, as Python devs expect. We believe we have a path forward for this, while retaining good error messages when a type doesn't conform, and fitting into other design goals of the language. It will be a novel approach, avoiding complexity traps that other languages have fallen into. We'll reveal more as we make progress, stay tuned for updates.”
Ace! Thanks for the info. Excited to see what happens here. I have played with the current trait implementation and something feels a little “off” IMO with the current explicit declaration.