diff options
| author | kennytm <kennytm@gmail.com> | 2018-02-05 01:27:36 +0800 |
|---|---|---|
| committer | kennytm <kennytm@gmail.com> | 2018-02-05 01:27:36 +0800 |
| commit | e17ebdf344401c265ade3b02bb68df0d0485d71a (patch) | |
| tree | 69ae9abfb6aa69f17d7ed5bc4904c185b41c3f9d /src/libcore | |
| parent | 66d6c855bda49035cdf825625dbe423a2e1a2a6b (diff) | |
| parent | 196fad0d00bddd11074b5da32af2393abaac9a26 (diff) | |
| download | rust-e17ebdf344401c265ade3b02bb68df0d0485d71a.tar.gz rust-e17ebdf344401c265ade3b02bb68df0d0485d71a.zip | |
Rollup merge of #47892 - Badel2:const_type_id_of, r=oli-obk
Turn `type_id` into a constant intrinsic https://github.com/rust-lang/rust/issues/27745 The method `get_type_id` in `Any` is intended to support reflection. It's currently unstable in favor of using an associated constant instead. This PR makes the `type_id` intrinsic a constant intrinsic, the same as `size_of` and `align_of`, allowing `TypeId::of` to be a `const fn`, which will allow using an associated constant in `Any`.
Diffstat (limited to 'src/libcore')
| -rw-r--r-- | src/libcore/any.rs | 27 | ||||
| -rw-r--r-- | src/libcore/lib.rs | 1 |
2 files changed, 28 insertions, 0 deletions
diff --git a/src/libcore/any.rs b/src/libcore/any.rs index 338e5c7fd95..566bfe2a3fb 100644 --- a/src/libcore/any.rs +++ b/src/libcore/any.rs @@ -367,9 +367,36 @@ impl TypeId { /// } /// ``` #[stable(feature = "rust1", since = "1.0.0")] + #[cfg(stage0)] pub fn of<T: ?Sized + 'static>() -> TypeId { TypeId { t: unsafe { intrinsics::type_id::<T>() }, } } + + /// Returns the `TypeId` of the type this generic function has been + /// instantiated with. + /// + /// # Examples + /// + /// ``` + /// use std::any::{Any, TypeId}; + /// + /// fn is_string<T: ?Sized + Any>(_s: &T) -> bool { + /// TypeId::of::<String>() == TypeId::of::<T>() + /// } + /// + /// fn main() { + /// assert_eq!(is_string(&0), false); + /// assert_eq!(is_string(&"cookie monster".to_string()), true); + /// } + /// ``` + #[stable(feature = "rust1", since = "1.0.0")] + #[rustc_const_unstable(feature="const_type_id")] + #[cfg(not(stage0))] + pub const fn of<T: ?Sized + 'static>() -> TypeId { + TypeId { + t: unsafe { intrinsics::type_id::<T>() }, + } + } } diff --git a/src/libcore/lib.rs b/src/libcore/lib.rs index 2e1f925c49a..59a296c2a76 100644 --- a/src/libcore/lib.rs +++ b/src/libcore/lib.rs @@ -91,6 +91,7 @@ #![feature(untagged_unions)] #![feature(unwind_attributes)] #![feature(doc_spotlight)] +#![feature(rustc_const_unstable)] #[prelude_import] #[allow(unused)] |
