Interfaces or Abstract Classes

I am learning the language, coming from .NET and Python. I am trying to implement a feature that is only aware of the of signature of another feature, and isn't concerned with its implementation details. Naturally, I reached for the traits system, but hit a brick wall because I found out you can't specify the return type of a function to be a trait, and I don't think you can specify a variable's type to be a trait either. I got partly around this writing a function that takes in the trait... I'm probably not making a ton of sense. Suppose I have feature A, that I want to be swappable at runtime with feature B based on a runtime configuration. Traditionally I would do this with interfaces, and traits seem like the closest thing. Is there a way to do this in Mojo?
5 Replies
Darkmatter
Darkmatter2mo ago
Mojo as a language is currently WIP, and the feature that you want is still being worked on. For now, use generics to generate both codepaths and use control flow to choose which path to take based on the run-time configuration.
xentropy
xentropy2mo ago
Awesome. Thank you!
benny
benny2mo ago
I think you may also be missing this kind of syntax
func getInt[T: Intable]() -> T:
return 1
func getInt[T: Intable]() -> T:
return 1
Im not sure if that example works but my point is you never declare a trait as an actual type, rather a type of a type, meaning it must be passed as an argument that is then used to type a parameter, let me know if that helps at all
Darkmatter
Darkmatter2mo ago
There are plenty of usecases for wanting something like Rust’s dyn traits, namely dynamic dispatch.
BSeiler
BSeiler2mo ago
The mojo team calls these “existential types” and are on the to do list. I haven’t seen any ETA though.
Want results from more Discord servers?
Add your server