Is it possible to use `impl Trait` as a function’s return type in a trait definition?

As trentcl mentions, you cannot currently place impl Trait in the return position of a trait method.

From RFC 1522:

impl Trait may only be written within the return type of a freestanding or inherent-impl function, not in trait definitions or any non-return type position. They may also not appear in the return type of closure traits or function pointers, unless these are themselves part of a legal return type.

  • Eventually, we will want to allow the feature to be used within traits […]

For now, you must use a boxed trait object:

trait A {
    fn new() -> Box<dyn A>;
}

See also:

  • Is it possible to have a constructor function in a trait?
  • Why can a trait not construct itself?
  • How do I return an instance of a trait from a method?

Nightly only

If you wish to use unstable nightly features, you can use existential types (RFC 2071):

// 1.67.0-nightly (2022-11-13 e631891f7ad40eac3ef5)
#![feature(type_alias_impl_trait)]
#![feature(return_position_impl_trait_in_trait)]

trait FromTheFuture {
    type Iter: Iterator<Item = u8>;

    fn returns_associated_type(&self) -> Self::Iter;

    // Needs `return_position_impl_trait_in_trait`
    fn returns_impl_trait(&self) -> impl Iterator<Item = u16>;
}

impl FromTheFuture for u8 {
    // Needs `type_alias_impl_trait`
    type Iter = impl Iterator<Item = u8>;

    fn returns_associated_type(&self) -> Self::Iter {
        std::iter::repeat(*self).take(*self as usize)
    }

    fn returns_impl_trait(&self) -> impl Iterator<Item = u16> {
        Some((*self).into()).into_iter()
    }
}

fn main() {
    for v in 7.returns_associated_type() {
        println!("type_alias_impl_trait: {v}");
    }

    for v in 7.returns_impl_trait() {
        println!("return_position_impl_trait_in_trait: {v}");
    }
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)