Anonymous object implementing a trait

  1. We have
pub trait FooT {
...
}
  1. Now, normally to create an object that implements FooT, we have to do:
pub struct SomeObject { ... }
impl FooT for SomeObject
  1. My question is: without declaring struct SomeObject, is it possible to create an ANONYMOUS object that implements FooT ? This woujld probably involve the use of closures, but I have no idea.

What do you need this for?

I have a struct whose sole purpose in life is to:

  • package up some existing structs
  • in a way to implement a pre-existing trait

This struct is never used for anything else -- and it seems like it could be anonymous.

===

Squiting a big, a "closure" is sorta like an anonymous struct that only implements one function. I'd like to this this a step further and have the closure support multiple functions / an entire trait.

I see. I don't think there's something like that in Rust.

People sometimes implement reusable structs that implement a bunch of traits in a generic way, e.g. the either crate.

You still have to create your struct somewhere. But:

  • There's no need to make the type public, you can return it as either Box<dyn FooT> or impl FooT.
  • You can have the struct declared inside the function, so nobody can really get to it, and it is declared pretty close to where you use it or return from.

It's not really anonymous, but there's no way to name it by someone else. Something like this:

pub trait FooT {
    ...
}

fn anon_foot() -> impl FooT {
    struct A(int, String);
    impl FooT for A {}
    A(42, "Hello".to_owned())
}

There isn't direct syntax sugar, like with closures, but you probably could throw something together as a macro (or maybe even someone did ‒ try searching for such a macro on crates.io).

(by the way, if that T means Trait, then doing that kind of isn't the usual habit in Rust).

4 Likes

TIL you can create structs inside of functions. (seems weird, but why not?)