Search code examples
rusttype-parameter

How do I provide type parameters to trait functions that don't take self?


This doesn't compile:

pub trait TheTrait<T> {
    pub fn without_self() -> T;
    pub fn with_self(&self) -> T {
        TheTrait::without_self()
    }
}

because the compiler can't figure out the type parameters for TheTrait::without_self(). I want something like TheTrait<T>::without_self(), but I can't find a syntax that works. How do I provide the type parameter to without_self?


Solution

  • Editor's note: This answer is outdated as of Rust 1.0

    If there's no Self or self in the function signature, it's not callable, at least until UFCS is implemented. For now, you can take Option<Self> as an argument, and call with None::<Self> as a work-around.

    pub trait TheTrait<T> {
        fn without_self(Option<Self>) -> T;
        fn with_self(&self) -> T {
            TheTrait::without_self(None::<Self>)
        }
    }