Skip to content

borrowed_box warnings on functions that returns U<&V> where V happens to be Box<T> #11833

Open
@OxidizedLoop

Description

@OxidizedLoop

Summary

As per the code bellow HashMap.get() returns type Option<&V>, V just happens to be Box<i32> leading to the return type of SuperHashMapsh_get() being Option<&Box<i32>>. We then get the borrowed_box warning on the resulting &Box<T>.

This happens not just with Option<&V> but to any function that the return value is a call to a different function that returns U<&V> where V is a Box<T>.

I would suggest for the lint not to trigger when &Box<T> is the result of a functioning returning U<&V> where V is Box<T> as its clear that the problem is not created by mistakenly creating a &Box<T>. Changing it to &T is not the correct solution as it would involve destroying U, changing &Box<T> to a &T, and creating a new U to hold &T .

I assume this could be fixed by checking if the return value of a function like sh_get() is the result of a function like get() that returns U<&V> and not give a warning in this situation.

Lint Name

clippy::borrowed_box

Reproducer

playground link

I tried this code: (I'm only using Box<i32> for the MRE.)

use std::{collections::HashMap, option::Option};
pub struct SuperHashmap {
    hashmap: HashMap<String, Box<i32>>,
}
impl SuperHashMap {
    pub fn sh_get(&self, key: String) -> Option<&Box<i32>> {
        self.hashmap.get(&key)
    }
}

I saw this happen:

warning: you seem to be trying to use `&Box<T>`. Consider using just `&T`
 --> src/lib.rs:6:49
  |
6 |     pub fn sh_get(&self, key: String) -> Option<&Box<i32>> {
  |                                                 ^^^^^^^^^ help: try: `&i32`
  |
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#borrowed_box
  = note: `#[warn(clippy::borrowed_box)]` on by default


I expected to see this happen:

No warning from clippy

Version

rustc 1.76.0-nightly (6b771f6b5 2023-11-15)
binary: rustc
commit-hash: 6b771f6b5a6c8b03b6322a9c77ac77cb346148f0
commit-date: 2023-11-15
host: x86_64-pc-windows-msvc
release: 1.76.0-nightly
LLVM version: 17.0.5

Also occurs in stable as seen in the playground link above.

Additional Labels

@rustbot label +T-middle

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-bugCategory: Clippy is not doing the correct thingI-false-positiveIssue: The lint was triggered on code it shouldn't haveT-middleType: Probably requires verifiying types

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions