Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making a negative trait in Rust, opposite of Sized (Unsized)

Tags:

rust

traits

I've figured i need a trait which is the opposite of Sized. Anything which is not Sized should have this trait. I need this in order to avoid conflicting implementation when specializing another trait elsewhere in my code differently for sized and non-sized types. Using ?Sized in this case does not work as it leads to conflicting implementations.

For this i've defined an auto-trait, and then made a negative impl for T in the cases where T: Sized.

I'm using rust-nightly with features auto_traits and negative_impls turned on in main.rs:

#![feature(auto_traits)]
#![feature(negative_impls)]

For some reason dyn Any does not implement Unsized, despite also not implementing Sized. Is there some implicit Sized requirement in the auto implementation or something? Ideally i'd want every type to either extend Sized, or Unsized with no overlap.

use std::any::Any;

use static_assertions::assert_impl_one;

pub auto trait Unsized {}

impl<T> !Unsized for T
where
    T: Sized
{
    
}

assert_not_impl_any!(dyn Any: Sized); // Succeeds! -> dyn Any is not Sized, as expected.
assert_impl_one!(dyn Any: Unsized); // Fails! -> dyn Any is not Unsized either??? It should be.

Why does the trait Unsized not get implemented for things which are obviously not Sized?

Removing the negative implementation yields the same assertion results. dyn Any is still not Unsized.

like image 799
sigurd4 Avatar asked Oct 27 '25 03:10

sigurd4


1 Answers

Auto-traits are not implemented for dyn Traits, unless they explicitly opt them in (dyn Any + Sync, dyn Any + Unsized).

The reason is that auto traits have little value if we consider the dyn Trait itself, as it has no information about the actual type. Usually, what we want is that the underlying type implements the auto-trait, not the dyn Trait itself. Think about Sync, for example: we cannot tell if dyn Any is Sync or not, because we don't know what data it contains. Only the actual type can be Sync or not. That is why dyn Trait never implement an auto trait, unless the user explicitly say it will bring only types that implement it (dyn Trait + AutoTrait).

like image 138
Chayim Friedman Avatar answered Oct 30 '25 11:10

Chayim Friedman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!