MFlamer
MFlamer

Reputation: 2440

Another rust generics exercise

I'm trying to implement a Monad like trait in Rust. Mostly just for fun and to get familiar with the type system. I'm pretty sure I will not be able to fully implement a Monad trait due to the lack of "higher kinds" as explained in this reddit discussion, but I want to see how close I can get. For some reason I can't get this code to compile. Seems like it should. Can someone explain why?

trait Monad<T> {
    fn lift(val: T) -> Self;
}

struct Context<T>{ 
    val: T 
}

impl<T> Monad<T> for Context<T> {
    fn lift(x: T) -> Context<T> {
        Context{val: x}
    }
}

fn main() { 
    let c:Context<int> = Context<int>::lift(5i);
}

Upvotes: 7

Views: 1390

Answers (1)

Luqman
Luqman

Reputation: 1576

Static methods defined in a trait must be called through it. So, you'd have:

let c: Context<int> = Monad::lift(5);

Upvotes: 7

Related Questions