-
Notifications
You must be signed in to change notification settings - Fork 1.6k
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
Move the 'static bound of Any to the methods. #2280
Comments
This is a breaking change. |
I think anything like this requires ATC tricks according to #1849 |
Is there anything wrong with the two line replacement pub trait MyAny { }
impl<T: ?Sized> MyAny for T { } (I mean, other than the obvious it's not in the standard lib?) |
@ExpHP yes, it's enough for the use case. However for it to act as a 'top type' here, if there're more |
This would help with use std::any::TypeId;
use std::fmt;
pub trait Unknown {
fn type_id(&self) -> TypeId
where
Self: 'static;
}
impl<T: ?Sized> Unknown for T {
fn type_id(&self) -> TypeId
where
T: 'static,
{
TypeId::of::<T>()
}
}
macro_rules! imp {
($bound:ty) => {
// Not providing `+ '_` to possibly allow TypeId debug information
impl fmt::Debug for $bound {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.pad("Unknown")
}
}
impl $bound {
pub fn is<T: 'static>(&self) -> bool {
let t = TypeId::of::<T>();
let concrete = self.type_id();
t == concrete
}
pub fn downcast_ref<T: 'static>(&self) -> Option<&T> {
if self.is::<T>() {
unsafe { Some(&*(self as *const dyn Unknown as *const T)) }
} else {
None
}
}
pub fn downcast_mut<T: 'static>(&mut self) -> Option<&mut T> {
if self.is::<T>() {
unsafe { Some(&mut *(self as *mut dyn Unknown as *mut T)) }
} else {
None
}
}
}
};
}
imp!(dyn Unknown);
imp!(dyn Unknown + Send);
imp!(dyn Unknown + Send + Sync); |
Let's continue this in the form of an API Change Proposal in https://github.com/rust-lang/libs-team if someone is up for owning a concrete proposed path forward. |
In principle the trait
Any
works just like a 'top type' trait. However there's the unnecessary bound of 'static involved by the restrictions ofdowncast
method. So i propose that the 'static bound move to the methods, soAny
can act as a real 'top type' trait.Use case: When i want to erase the type of a value and just make sure it is alive until a certain point, currently there's no good way to do so. However, with the changes above, i can just put it into a
Box<Any + 'a>
.The text was updated successfully, but these errors were encountered: