Skip to content

Add rule to object safety? #756

Open
@ehuss

Description

@ehuss
Contributor

There seems to be a rule missing from the object safety list: https://github.com/rust-lang/reference/blob/master/src/items/traits.md#object-safety

I'm not sure how to properly word the rule, but it something along that lines that "Supertraits cannot reference Self as a type parameter".

This restriction was introduced in rust-lang/rust#22452.

Some examples:

trait Super<T: ?Sized> {}
trait WithSelf: Super<Self> {}
struct S;
impl<A> Super<A> for S {}
impl WithSelf for S {}
let obj: Box<dyn WithSelf> = Box::new(S);  // ERROR: `Self` in type parameter
// Slight variation using default type.
trait Super<T: ?Sized = Self> {}
trait WithSelf: Super {}
struct S;
impl Super for S {}
impl WithSelf for S {}
let obj: Box<dyn WithSelf> = Box::new(S);  // ERROR: `Self` in type parameter

Is it correct that this rule should be added to the list? If so, can someone write down the proper wording?

Activity

Centril

Centril commented on Feb 10, 2020

@Centril
Contributor
jmaargh

jmaargh commented on Dec 13, 2023

@jmaargh

This apparently doesn't only apply for supertraits that use Self as a type parameter, but also if the trait itself does (for example PartialEq appears to be non-object-safe as a result) because

trait PartialEq<Rhs = Self>

I suggest adding

  • A generic type parameter of this trait, or any of its supertraits, is not specified to be Self

together with an expanded example to show that this applies even when Self: ?Sized.

For reference, this is the compiler error describing the same rule:

5  | trait MyTrait: PartialEq {}
   |       -------  ^^^^^^^^^ ...because it uses `Self` as a type parameter
   |       |
   |       this trait cannot be made into an object...

Happy to make a PR where exact language can be agreed if this is desirable.

ehuss

ehuss commented on Feb 4, 2024

@ehuss
ContributorAuthor

I asked over at https://rust-lang.zulipchat.com/#narrow/stream/213817-t-lang/topic/object.20safety.20of.20Self.20in.20supertraits for some suggestions. Someone noted rust-lang/rust#88904 as a strange edge case, but I am uncertain if that is just a bug.

What you have suggested above sounds good to me, and would be happy to take a PR.

jmaargh

jmaargh commented on Feb 4, 2024

@jmaargh

Happy to. Will be delayed until I get permission from my new job but I don't see that being a problem.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @ehuss@Centril@jmaargh

        Issue actions

          Add rule to object safety? · Issue #756 · rust-lang/reference