rust-lang / rust-lang/rfcs

Reusable types and negative reasoning for marker traits

Open
#1,279 4 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

T-lang
Dominant language
Markdown
Stars
6.6k
Forks
1.7k
Avg merge
16h 14m
Merged PRs (30d)
1

Description

Currently the compiler is unable to reason about certain things in the type system that are obvious to the programmer. For example, a &mut T can never be Copy, and yet the compiler will reject the following:

trait Foo {}
impl<T: Copy> Foo for T {}
impl<'a, T> Foo for &'a mut T {}

Because it thinks they might overlap.

This is problematic because it makes it impossible to abstract over certain useful things, like whether a type is "reusable", ie. the set of types for which example2 is valid:

fn example1<T>(a: T) { }
fn example2(a: ReusableType) {
    example1(a);
    example1(a);
}

(This is not the same as T: Copy, because a &mut T would be valid here due to rust's automatic reborrowing)

If you try to represent this with a trait, you run into the problem above:


trait Reborrow {
    fn reborrow<R, F: FnOnce(Self) -> R>(&mut self, f: F) -> R;
}

impl<T: Copy> Reborrow for T {
    fn reborrow<R, F: FnOnce(Self) -> R>(&mut self, f: F) -> R {
        f(*self)
    }
}

impl<'a, T> Reborrow for &'a mut T {
    fn reborrow<R, F: FnOnce(Self) -> R>(&mut self, f: F) -> R {
        f(*self)
    }
}

This particular example could be solved by making the compiler aware that &mut T can never be Copy.

In general, the compiler could apply negative reasoning to marker traits: since implementing a marker trait for an existing type is already a breaking change, there's not the same backwards compatibility problem as there is with normal traits.

Contributor guide

No contributing guide indexed for this repository

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

Start with the overlapping impl and Reborrow examples in this issue, then review Rust's marker-trait and coherence rules. A useful outcome would define the proposed negative-reasoning behavior and its compatibility boundaries; no implementation files or tests are identified here.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
compilers
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.