[Feature Request] `where` clauses on trait methods
Open
@JoeLoser is already working on this.
Since Sep 9, 2026.
bug_feature_triaged
enhancement
feature:traits
feature:where-clauses
Kind=enhancement
mojo
Needs=design
Origin=github
Stage=conformance
Team: Mojo Compiler
- Dominant language
- Mojo
- Stars
- 29.8k
- Forks
- 3.2k
- PR merge metrics
- No merged PRs in 30d
Description
Review Mojo's priorities
- I have read the roadmap and priorities and I believe this request falls within the priorities.
What is your request?
Allow the following:
trait Trait1:
comptime OpIsAllowedWith[OtherType: Trait1]: Bool
def do_operation[OtherType: Trait1](self, other: OtherType) where Self.OpIsAllowedWith[OtherType]:
...
@fieldwise_init
struct Struct1(Trait1):
comptime OpIsAllowedWith[OtherType: Trait1] = Self == OtherType
def do_operation[OtherType: Trait1](self, other: OtherType) where Self.OpIsAllowedWith[OtherType]:
...
@fieldwise_init
struct Struct2(Trait1):
comptime OpIsAllowedWith[OtherType: Trait1] = OtherType == Self or OtherType == Struct3
def do_operation[OtherType: Trait1](self, other: OtherType) where Self.OpIsAllowedWith[OtherType]:
...
@fieldwise_init
struct Struct3(Trait1):
comptime OpIsAllowedWith[OtherType: Trait1] = OtherType == Self or OtherType == Struct2
def do_operation[OtherType: Trait1](self, other: OtherType) where Self.OpIsAllowedWith[OtherType]:
...
def main():
var s1_0 = Struct1()
var s1_1 = Struct1()
var s2 = Struct2()
var s3 = Struct3()
s1_0.do_operation(s1_1)
s1_0.do_operation(s2) # compile-time error
s2.do_operation(s2)
s2.do_operation(s3)
s2.do_operation(s1) # compile-time error
s3.do_operation(s3)
What is your motivation for this change?
This provides a workaround for one of the major use-cases of parametric traits, which is expressing "one to many" type relationships. The current way to do this more or less involves a "please stick this code in the function body" comment on the trait, which isn't great.
In particular, I'd really like this feature for:
- The IO API https://github.com/modular/modular/pull/4728
- Hardware abstraction (RISC-V especially)
- A few extra bits of stdlib complexity moved into plugin hooks
Any other details?
No response
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Assessment
This issue has not been assessed yet.