Any can store almost anything

The Rust compiler automatically implements Any for any data type, unless that data type contains non-static references. So, our Forward, Turn, and Stop structures that we used in the trait objects section already automatically implement Any, but something like this would not:

pub struct DoesNotHaveAnyTrait<'a> {
pub name: &'a str,
pub count: i32,
}

More accurately, DoesNotHaveAnyTrait only has the Any trait when 'a is equal to 'static, which it is if we use a simple string expression such as this is a static string to initialize it, but not if we use some other mechanism for retrieving or constructing an &str value.

The error the compiler will give if we try something impossible along these lines will probably be about lifetimes rather than explicitly about the Any trait, as in the following example:

Do you see the note? The code that caused the error was trying to create an &dyn Any, which told the compiler that the 'a lifetime needed to be compatible with 'static, which told it that the lifetime of wrong.as_str() was too short, so it reported an error.

Usually, that's not much of a problem, because we have several other reasons to avoid using non-static references in our data types, and we can use String, Vec, Box, and the like to achieve the same result. It's just something to keep in mind.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.38.92