Function that can return any struct that implements a Trait

You can use enums inside of enums, but you cannot restrict the value to one variant of the enum (ie use the enum variant as a top-level type).

Example: Rust Playground

1 Like

I'd like to emphasize that rust does have sufficient runtime type information for Go-like switching on types via the builtin Any trait, though there are caveats: it's not applicable to types that are constrained by a non-static lifetime since lifetime is strictly a compile-time construct and cannot safely be reconstructed at run-time. So, as long as your types (automatically) implement Any, you can define a trait on which you can iteratively try to cast to different concrete types. The ergonomics for doing that isn't built into the language, and you need any of the many downcasting crates. I authored downcast-rs, which uses only safe code and supports type-parametrized traits.

That being said, you probably want an enum for your case.

1 Like