Macro static_assertions::assert_obj_safe [] [src]

macro_rules! assert_obj_safe {
    ($($xs:ty),+ $(,)*) => { ... };
    ($label:ident; $($xs:tt)+) => { ... };
}

Asserts that the traits are object-safe.

This is useful for when changes are made to a trait that accidentally prevent it from being used as an object. Such a case would be adding a generic method and forgetting to add where Self: Sized after it. If left unnoticed, that mistake will affect crate users and break both forward and backward compatibility.

Examples

assert_obj_safe!(basic; Send, Sync, AsRef<str>);

mod inner {
    // Works with traits that are not in the calling module
    pub trait BasicTrait {
        fn foo(&self);
    }
}

trait MySafeTrait {
    fn bar(&self) -> u32;
}

fn main() {
    assert_obj_safe!(MySafeTrait);
    assert_obj_safe!(inner::BasicTrait);
}

Generics without where Self: Sized are not allowed in object-safe traits:

This code doesn't compile so be extra careful!
trait MyUnsafeTrait {
    fn baz<T>(&self) -> T;
}

assert_obj_safe!(MyUnsafeTrait);