Skip to content

Warn for passing Box<&dyn Any> to function taking &dyn std::any::Any #12800

Open
@Wumpf

Description

@Wumpf

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 &dyn Any: Since &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) { ... }

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-lintArea: New lints

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions