modular / modular/modular

[Feature Request] `where` clauses on trait methods

Open
#7,092 0 comments 0 reactions 1 assignee View on GitHub

@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
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:

Any other details?

No response

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.