RS.CLIPPY.COERCE_CONTAINER_TO_ANY
Coercing to `&dyn Any` when dereferencing could produce a `dyn Any` without coercion is usually not intended
This checker is a Clippy lint created by The Rust Project Contributors. The documentation shown here is a copy of the original documentation for: coerce_container_to_any. Copyright ©2025 The Rust Team. All rights reserved.
What it does
Protects against unintended coercion of references to container types to &dyn Any when the
container type dereferences to a dyn Any which could be directly referenced instead.
Why is this bad?
The intention is usually to get a reference to the dyn Any the value dereferences to,
rather than coercing a reference to the container itself to &dyn Any.
Example
Because Box<dyn Any> itself implements Any, &Box<dyn Any>
can be coerced to an &dyn Any which refers to the Box itself, rather than the
inner dyn Any.
let x: Box<dyn Any> = Box::new(0u32);
let dyn_any_of_box: &dyn Any = &x;
// Fails as we have a &dyn Any to the Box, not the u32
assert_eq!(dyn_any_of_box.downcast_ref::<u32>(), None);
Use instead:
let x: Box<dyn Any> = Box::new(0u32);
let dyn_any_of_u32: &dyn Any = &*x;
// Succeeds since we have a &dyn Any to the inner u32!
assert_eq!(dyn_any_of_u32.downcast_ref::<u32>(), Some(&0u32));