Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make Any an unsafe trait #67562

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 9 additions & 12 deletions src/libcore/any.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,19 +73,16 @@ use crate::intrinsics;
/// Most types implement `Any`. However, any type which contains a non-`'static` reference does not.
/// See the [module-level documentation][mod] for more details.
///
/// This trait is notably `unsafe`. However, this does not affect any use of
/// this trait in downstream code, as it is always safe to use `Any`. The reason
/// that `Any` is unsafe is that the standard library relies on its
Comment on lines +76 to +78
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This makes it sound like there'd be something odd here, but this is entirely normal for unsafe traits: they are unsafe to implement but safe to use.

/// implementation returning appropriate `TypeId`s for safe downcasting.
/// However, no code outside the standard library can implement `Any` as it
/// would overlap with the standard libaries impl for all `'static` types.
///
/// [mod]: index.html
// This trait is not unsafe, though we rely on the specifics of it's sole impl's
// `type_id` function in unsafe code (e.g., `downcast`). Normally, that would be
// a problem, but because the only impl of `Any` is a blanket implementation, no
// other code can implement `Any`.
//
// We could plausibly make this trait unsafe -- it would not cause breakage,
// since we control all the implementations -- but we choose not to as that's
// both not really necessary and may confuse users about the distinction of
// unsafe traits and unsafe methods (i.e., `type_id` would still be safe to call,
// but we would likely want to indicate as such in documentation).
#[stable(feature = "rust1", since = "1.0.0")]
pub trait Any: 'static {
pub unsafe trait Any: 'static {
/// Gets the `TypeId` of `self`.
///
/// # Examples
Expand All @@ -105,7 +102,7 @@ pub trait Any: 'static {
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<T: 'static + ?Sized> Any for T {
unsafe impl<T: 'static + ?Sized> Any for T {
fn type_id(&self) -> TypeId {
TypeId::of::<T>()
}
Expand Down