Should be more explicit that coercions aren't used to satisfy trait bounds.

Open
#850 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
2/5
Estimated time
1-3 hours
Newbie friendliness
48/100
Issue type
Documentation
Clarity
Mostly clear
Activity status
Stale
Tech stack
rust
Domain
documentation

Research direction

Start with the linked type coercions section in the Rust Reference and review its explanation of coercion sites. Use the provided generic-bound example to clarify that coercions do not satisfy inferred trait bounds, while an explicitly specified type can permit the coercion. Done means the section includes this distinction and an understandable example.

Written by the indexing model from the issue text.

Description

A-coercions

The section on type coercions should be more explicit that coercions aren't used to satisfy generic bounds. I've noticed some people getting caught off guard by that.

Here is an example of what I am talking about:


struct A(B);
struct B;

trait Trait {}
impl Trait for B {} 

impl std::ops::Deref for A {
    type Target = B;
    fn deref(&self) -> &B { &self.0 }
}

fn f<T: Trait>(t: &T) {}

fn main() {
    let a = A(B);
    
    // Error: the trait `Trait` is not implemented for `A`.
    f(&a);
    
    // Ok, since the trait bound was manually specified.
    f::<B>(&a);
}

I know the paragraph at the top says:

A coercion can only occur at certain coercion sites in a program; these are typically places where the desired type is explicit or can be derived by propagation from explicit types (without type inference).

However, adding an example, or even a dedicated section showing when type coercions wouldn't occur would better help explain the concept.

Dominant language
Rust
Stars
1.6k
Forks
607
Avg merge
1d 1h
Merged PRs (30d)
12

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.

More from rust-lang/reference

All issues in rust-lang/reference

Similar issues

More Rust issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.