Search code examples
pythonmojolang

Mojo compile time programming - specifying a type


I run the following in the Mojo Plyaground (https://playground.modular.com/) and get an error, what am I doing wrong?

struct MyPair[type:AnyType]:
    var first: type
    var second: type

    # We use 'fn' instead of 'def' here - we'll explain that soon
    fn __init__(inout self, first: type, second: type):
        self.first = first
        self.second = second

    fn __lt__(self, rhs: MyPair[type]) -> Bool:       
           return self.first < rhs.first or
              (self.first == rhs.first and
               self.second < rhs.second)
        
    fn __copyinit__(inout self, other: MyPair[type]):
        self.first = other.first
        self.second = other.second
        

def pairTest() -> Bool:
    let p = MyPair[Int](1, 2)
    let q = MyPair[Int](3, 4)
   
    return p < q 

I ran the above program and got the following error:

error: Expression [35]:16:30: 'type' does not implement the '__lt__' method
           return self.first < rhs.first or

Solution

  • Answered by DayDun from here https://github.com/modularml/mojo/discussions/261 21 minutes ago type here could be any type. If you pass it a dictionary type for example, it doesn't really make sense to call self.first < rhs.first, that's why it's complaining. The proper solution here is traits, so that you can say type isn't just any type, it is any type that can be compared. But until traits are implemented you'll have to use DType or something to specify numeric types.