How do I return an instance of a trait from a method?

Rust 1.26 and up

impl Trait now exists:

fn create_shader(&self) -> impl Shader {
    let shader = MyShader;
    shader
}

It does have limitations, such as not being able to be used in a trait method and it cannot be used when the concrete return type is conditional. In those cases, you need to use the trait object answer below.

Rust 1.0 and up

You need to return a trait object of some kind, such as &T or Box<T>, and you’re right that &T is impossible in this instance:

fn create_shader(&self) -> Box<Shader> {
    let shader = MyShader;
    Box::new(shader)
}

See also:

Leave a Comment