rust-lang / rust-lang/rust

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

Open
#132,133 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-diagnostics D-confusing T-compiler
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

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

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

Reproduce the example from src/main.rs with rustc 1.81.0 and confirm the diagnostics involving Borrow and Ref::map. Investigate how the compiler resolves the borrow call when std::borrow::Borrow is imported. Done means the reported example compiles successfully and prints elem without requiring unnecessary changes to the code.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.