rust-lang / rust-lang/rfcs

Safe coercions for references of repr(transparent) types

Open
#3,066 15 comments 16 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

Idea: types which are repr(transparent) whose can be constructed in the current scope should be coercible via as. Going to post this here because I don't really have the time to write an RFC or file an MCP, but this is something I've thought for a while and haven't really seen concretely mentioned anywhere.

Example:

mod scope {
    #[repr(transparent)]
    pub struct Wrapper<T>(T);
    impl<T> Wrapper<T> {
        pub fn wrap(val: &T) -> &Wrapper<T> {
            val as &Wrapper<T> // okay because constructor `Wrapper` is accessible here
        }
        pub fn wrap_slice(slice: &[T]) -> &[Wrapper<T>] {
            val as &[Wrapper<T>] // also okay to coerce inside types
        }
    }
}

fn cant_wrap<T>(val: &T) -> &Wrapper<T> {
    val as &Wrapper<T> // will fail because constructor `Wrapper` isn't accessible here
}

Essentially, right now, this is defined to not invoke undefined behaviour, ever, due to the presence of repr(transparent). However, there is no way to actually do this with safe code. The closest you can do is pointer casts, which ultimately still require an unsafe block to convert the pointers back into valid references, or transmutes, which are inherently unsafe.

I know that there are plans to make safe transmutation work, but I feel like this kind of coercion would also be nice to have.

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 proposal and its repr(transparent) reference and slice examples in this issue. Research Rust's existing coercion and safe-transmutation plans, then turn the idea into the requested RFC or MCP with defined accessibility rules, type-checking behavior, and safety guarantees. Done means the design is specified well enough for the Rust project to evaluate.

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
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.