rust-lang / rust-lang/rust-clippy

borrowed_box should not be emitted for mutable boxed trait object

Open
#1,845 8 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

Hello.
The borrowed_box suggestion can be a false positive for mutable boxed trait object, because it seems there's no way to apply the suggestion (it only works for immutable boxed trait object).

For example, the following code triggers this warning:

fn get_mut<'a>(map: &'a mut HashMap<String, Box<Display>>, key: &str) -> Option<&'a mut Box<Display>> {
    map.get_mut(key)
}

But if I try to fix it by:

fn get_mut<'a>(map: &'a mut HashMap<String, Box<Display>>, key: &str) -> Option<&'a mut Display> {
    map.get_mut(key)
        .map(AsMut::as_mut)
}

I get a compilation error:

error[E0308]: mismatched types
  --> src/main.rs:12:5
   |
12 | /     map.get_mut(key)
13 | |         .map(AsMut::as_mut)
   | |___________________________^ lifetime mismatch
   |
   = note: expected type `std::option::Option<&'a mut std::fmt::Display + 'a>`
              found type `std::option::Option<&mut std::fmt::Display + 'static>`
note: the lifetime 'a as defined on the function body at 11:1...
  --> src/main.rs:11:1
   |
11 | / fn get_mut<'a>(map: &'a mut HashMap<String, Box<Display>>, key: &str) -> Option<&'a mut Display> {
12 | |     map.get_mut(key)
13 | |         .map(AsMut::as_mut)
14 | | }
   | |_^
   = note: ...does not necessarily outlive the static lifetime

(To be honest, I don't understand why I get this error for returning a mutable reference, but not for an immutable reference.)

Thanks to remove the warning in this case.

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

Start at the borrowed_box lint and reproduce the mutable boxed trait-object example from the issue. Trace why the suggestion is emitted, then verify that this case no longer warns while the applicable immutable case retains its existing behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
devtools
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.