Is ` -> impl Any` mean, that I can return a type dynamically or?

What is difference between impl Trait and impl Any?

Yes you can write impl Any and that allows you to return any static type.

impl Trait is just a name for the feature that allows you to write impl ? where you can put any trait name in place of ?. You would probably never actually write impl Trait verbatim in your code, because that would mean you have a trait named “Trait” which seems weird.

The feature is documented at Redirecting... .

1 Like

And what is the drawback of impl Any?

Any does not provide any functionality. You can't call any methods on an impl Any or do practically anything else with it without first downcasting it.

use std::any::Any;

fn return_one() -> i32 {
    1
}

fn return_one_any() -> impl Any {
    1
}

fn main() {
    let a = return_one();
    let b = return_one_any();
    println!("{} + {} = {}", a, b, a + b);
}
error[E0277]: cannot add `impl std::any::Any` to `i32`
  --> src/main.rs:14:38
   |
14 |     println!("{} + {} = {}", a, b, a + b);
   |                                      ^ no implementation for `i32 + impl std::any::Any`
   |
   = help: the trait `std::ops::Add<impl std::any::Any>` is not implemented for `i32`

error[E0277]: `impl std::any::Any` doesn't implement `std::fmt::Display`
  --> src/main.rs:14:33
   |
14 |     println!("{} + {} = {}", a, b, a + b);
   |                                 ^ `impl std::any::Any` cannot be formatted with the default formatter
   |
   = help: the trait `std::fmt::Display` is not implemented for `impl std::any::Any`
   = note: in format strings you may be able to use `{:?}` (or {:#?} for pretty-print) instead
   = note: required by `std::fmt::Display::fmt`
1 Like

Any is one of the traits, so impl Any is an example of a feature generally referred to as impl Trait.

Any has some dynamic behavior itself, but it's probably not what you want.

impl Trait itself is not dynamic. It behaves as if you used one specific type only. You just don't have to write the full name of the type.

dyn Trait is dynamic.