Description
What it does
Issue a warning if a function takes any of
&dyn std::any::Any
&mut dyn std::any::Any
The recommendation is to either use an existing trait type or create a "marker trait" to specify what the method can actually process in order to avoid passing (by accident) object references of unexpected types.
EDIT: Only warn when Box<&dyn Any>
is passed as-is. Recommend box.as_ref()
Advantage
Beside the obvious advantages of a more concrete type, there's major pitfalls with Since &dyn Any
:&Box<Any>
itself implements Any
, it can easily happen that one accidentally passes the box directly instead of the desired box.as_ref()
. This can be the cause of quite hard to debug issues.
Drawbacks
While it's more often than not a shortcut for not defining a trait type, there are likely legitimate usecases for passing &dyn Any
(examples?)
Example
Updated suggestion:
fn func(value: &dyn std::any::Any) { ... }
func(box);
Could be written as:
fn func(value: &dyn std::any::Any) { ... }
func(box.as_ref());
Previous suggestion:
fn func(value: &dyn std::any::Any) { ... }
Could be written as:
fn func(value: &dyn MyTrait) { ... }