mojo
mojo copied to clipboard
Conditional Trait Conformance
Review Mojo's priorities
- [X] I have read the roadmap and priorities and I believe this request falls within the priorities.
What is your request?
I believe it would be nice for there to be conditional trait conformance in structs. This could be achieved through a a decorator that is passed static tuples that contain a type, the trait, and the struct value that needs to conform to this.
Example use case:
@value
struct SpecialStruct[T]:
var x: T
var y: T
@conditional((T, Stringable, Self.x))
fn __str__(self) -> String raises:
# raises in case T does not conform
return self.x
@conditional((T, Intable, Self.x), (T, Intable, Self.y))
fn mult_vals(self) -> Int raises:
# tuple ao you can use multiple struct variables
return self.x * self.y
What is your motivation for this change?
It would allow for more flexibility and be nice when a programmer knows if something will work.
Any other details?
Could be implemented in other ways but the idea/concept is still pretty important
Some alternate ideas for syntax include:
trait Purchaseable:
fn buy(): …
struct Array[T]:
fn buy() if conforms[T, Purchaseable] raises: …
Or
trait Purchaseable:
fn buy(): …
struct Array[T: AnyType](Purchaseable if T): …
Or (by far my least favorite as it requires another set of indentation)
struct Optional[T]:
# …
if conforms[T, CollectionElement]:
fn blah():
pass
With the last one there should, in my opinion, also be a way to not make another layer of indentation. In my experience you almost never need more than three layers of indentation and excessive layers are ugly. This is why many opt for guard clauses instead of layered ifs. You could say that it's because of the function definition, and thats true, but there's ways to not need the if statement or put in it a way that doesn't need more indentation
I believe this is related to https://github.com/modularml/mojo/issues/1876
Yes, thank you, closing in favor of #1876
What do you think of the proposed syntax, if I may @gabrieldemarmiesse?
I have no opinion on the syntax, everything is fine by me