Skip to content

Code Fails to Compile with Unnecessary use std::borrow::Borrow; #132133

Open
@zhristophe

Description

@zhristophe

I tried this code:

use std::borrow::Borrow;

struct Node<T> {
    elem: T,
}

fn main() {
    let a = Some(Rc::new(RefCell::new(Node { elem: 1 })));
    let b = a
        .as_ref()
        .map(|node| Ref::map(node.borrow(), |node| &node.elem));
    print!("{:?}", b);
}

I expected to see this happen: The code should compile successfully and print the value of elem.

Instead, this happened: The code fails to compile with an error indicating that Borrow is not resolved, leading to compilation failure. If I comment out the seemingly unnecessary use std::borrow::Borrow;, the code can compile.

Meta

rustc --version --verbose:

rustc 1.81.0 (eeb90cda1 2024-09-04)
Backtrace

error[E0282]: type annotations needed for `&_`
  --> src/main.rs:39:46
   |
39 |         .map(|node| Ref::map(node.borrow(), |node| &node.elem));
   |                                              ^^^^   --------- type must be known at this point
   |
help: consider giving this closure parameter an explicit type, where the type for type parameter `T` is specified
   |
39 |         .map(|node| Ref::map(node.borrow(), |node: &T| &node.elem));
   |                                                  ++++

error[E0609]: no field `elem` on type `&_`
  --> src/main.rs:39:58
   |
39 |         .map(|node| Ref::map(node.borrow(), |node| &node.elem));
   |                                                          ^^^^ unknown field

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsD-confusingDiagnostics: Confusing error or lint that should be reworked.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions