Skip to content

borrowed_box should not be emitted for mutable boxed trait object #1845

Open
@antoyo

Description

@antoyo

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-documentationArea: Adding or improving documentation

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions