rust-lang / rust-lang/rust-clippy

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

Open
#12,800 3 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

A-lint
Dominant language
Rust
Stars
13.5k
Forks
2.2k
Avg merge
2d 10h
Merged PRs (30d)
32

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 &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) { ... }

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

No source file, test, or entry point is named in the issue. Start by locating existing Clippy lints that inspect function arguments and calls involving std::any::Any. Done means warning only when Box<&dyn Any> is passed directly to a function accepting &dyn Any or &mut dyn Any, with a recommendation to use box.as_ref().

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
tooling
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.