Box and Any

When a variable's type is Box<dyn Any>, it acts much like an &dyn Any, but gains a new feature. A normal &dyn Any has a downcast_ref function that we can use to get a reference to the contained value, if we know what type to use to extract it. Now, &dyn mut Any adds a downcast_mut that we can use to get a mutable reference. When we have a Box<dyn Any>, we have access to both of those functions, but we can also call a plain downcast function to move the contained value out of the Any and into a variable of the correct type. This consumes the Box and the Any, and gives us back a new Box containing the data value with its correct data type.

Don't forget that we need to have use std::any::Any; in our code if we're going to use the Any trait.

We can create a boxed Any almost the same way we created a boxed Person:

let jill: Box<dyn Any> = Box::new(Person { name: "Jill".to_string(), validated: false });

The only difference here is that we're telling Rust that we want the jill variable to contain a Box<dyn Any> instead of letting it decide for itself that the variable contains a Box<Person>.

Now, to access the contained Person, we can do this:

let real_jill = jill.downcast::<Person>().unwrap();
println!("{}", real_jill.name);

Like the other downcast functions, we need to specify which concrete data type we're downcasting for. The downcast function returns a Result, which contains a Box<Person> if it's successful. Once we have a Box<Person>, we can do whatever we like with the Person value it contains.

The unwrap function we're calling here consumes a Result and returns its contained value if it's a success, or terminates the program with an error message if it's a failure. We use unwrap to handle a Result when we're very sure that it's going to be a success.

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

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