]> git.lizzy.rs Git - rust.git/blob - src/libcore/any.rs
466750fc7d2c63035f6f4cc46cba596ccf5827fe
[rust.git] / src / libcore / any.rs
1 //! This module implements the `Any` trait, which enables dynamic typing
2 //! of any `'static` type through runtime reflection.
3 //!
4 //! `Any` itself can be used to get a `TypeId`, and has more features when used
5 //! as a trait object. As `&dyn Any` (a borrowed trait object), it has the `is`
6 //! and `downcast_ref` methods, to test if the contained value is of a given type,
7 //! and to get a reference to the inner value as a type. As `&mut dyn Any`, there
8 //! is also the `downcast_mut` method, for getting a mutable reference to the
9 //! inner value. `Box<dyn Any>` adds the `downcast` method, which attempts to
10 //! convert to a `Box<T>`. See the [`Box`] documentation for the full details.
11 //!
12 //! Note that `&dyn Any` is limited to testing whether a value is of a specified
13 //! concrete type, and cannot be used to test whether a type implements a trait.
14 //!
15 //! [`Box`]: ../../std/boxed/struct.Box.html
16 //!
17 //! # Examples
18 //!
19 //! Consider a situation where we want to log out a value passed to a function.
20 //! We know the value we're working on implements Debug, but we don't know its
21 //! concrete type. We want to give special treatment to certain types: in this
22 //! case printing out the length of String values prior to their value.
23 //! We don't know the concrete type of our value at compile time, so we need to
24 //! use runtime reflection instead.
25 //!
26 //! ```rust
27 //! use std::fmt::Debug;
28 //! use std::any::Any;
29 //!
30 //! // Logger function for any type that implements Debug.
31 //! fn log<T: Any + Debug>(value: &T) {
32 //!     let value_any = value as &dyn Any;
33 //!
34 //!     // Try to convert our value to a `String`. If successful, we want to
35 //!     // output the String`'s length as well as its value. If not, it's a
36 //!     // different type: just print it out unadorned.
37 //!     match value_any.downcast_ref::<String>() {
38 //!         Some(as_string) => {
39 //!             println!("String ({}): {}", as_string.len(), as_string);
40 //!         }
41 //!         None => {
42 //!             println!("{:?}", value);
43 //!         }
44 //!     }
45 //! }
46 //!
47 //! // This function wants to log its parameter out prior to doing work with it.
48 //! fn do_work<T: Any + Debug>(value: &T) {
49 //!     log(value);
50 //!     // ...do some other work
51 //! }
52 //!
53 //! fn main() {
54 //!     let my_string = "Hello World".to_string();
55 //!     do_work(&my_string);
56 //!
57 //!     let my_i8: i8 = 100;
58 //!     do_work(&my_i8);
59 //! }
60 //! ```
61
62 #![stable(feature = "rust1", since = "1.0.0")]
63
64 use crate::fmt;
65 use crate::intrinsics;
66
67 ///////////////////////////////////////////////////////////////////////////////
68 // Any trait
69 ///////////////////////////////////////////////////////////////////////////////
70
71 /// A trait to emulate dynamic typing.
72 ///
73 /// Most types implement `Any`. However, any type which contains a non-`'static` reference does not.
74 /// See the [module-level documentation][mod] for more details.
75 ///
76 /// [mod]: index.html
77 #[stable(feature = "rust1", since = "1.0.0")]
78 pub trait Any: 'static {
79     /// Gets the `TypeId` of `self`.
80     ///
81     /// # Examples
82     ///
83     /// ```
84     /// use std::any::{Any, TypeId};
85     ///
86     /// fn is_string(s: &dyn Any) -> bool {
87     ///     TypeId::of::<String>() == s.type_id()
88     /// }
89     ///
90     /// assert_eq!(is_string(&0), false);
91     /// assert_eq!(is_string(&"cookie monster".to_string()), true);
92     /// ```
93     #[stable(feature = "get_type_id", since = "1.34.0")]
94     fn type_id(&self) -> TypeId;
95 }
96
97 #[stable(feature = "rust1", since = "1.0.0")]
98 impl<T: 'static + ?Sized > Any for T {
99     fn type_id(&self) -> TypeId { TypeId::of::<T>() }
100 }
101
102 ///////////////////////////////////////////////////////////////////////////////
103 // Extension methods for Any trait objects.
104 ///////////////////////////////////////////////////////////////////////////////
105
106 #[stable(feature = "rust1", since = "1.0.0")]
107 impl fmt::Debug for dyn Any {
108     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
109         f.pad("Any")
110     }
111 }
112
113 // Ensure that the result of e.g., joining a thread can be printed and
114 // hence used with `unwrap`. May eventually no longer be needed if
115 // dispatch works with upcasting.
116 #[stable(feature = "rust1", since = "1.0.0")]
117 impl fmt::Debug for dyn Any + Send {
118     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
119         f.pad("Any")
120     }
121 }
122
123 #[stable(feature = "any_send_sync_methods", since = "1.28.0")]
124 impl fmt::Debug for dyn Any + Send + Sync {
125     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
126         f.pad("Any")
127     }
128 }
129
130 impl dyn Any {
131     /// Returns `true` if the boxed type is the same as `T`.
132     ///
133     /// # Examples
134     ///
135     /// ```
136     /// use std::any::Any;
137     ///
138     /// fn is_string(s: &dyn Any) {
139     ///     if s.is::<String>() {
140     ///         println!("It's a string!");
141     ///     } else {
142     ///         println!("Not a string...");
143     ///     }
144     /// }
145     ///
146     /// is_string(&0);
147     /// is_string(&"cookie monster".to_string());
148     /// ```
149     #[stable(feature = "rust1", since = "1.0.0")]
150     #[inline]
151     pub fn is<T: Any>(&self) -> bool {
152         // Get `TypeId` of the type this function is instantiated with.
153         let t = TypeId::of::<T>();
154
155         // Get `TypeId` of the type in the trait object.
156         let concrete = self.type_id();
157
158         // Compare both `TypeId`s on equality.
159         t == concrete
160     }
161
162     /// Returns some reference to the boxed value if it is of type `T`, or
163     /// `None` if it isn't.
164     ///
165     /// # Examples
166     ///
167     /// ```
168     /// use std::any::Any;
169     ///
170     /// fn print_if_string(s: &dyn Any) {
171     ///     if let Some(string) = s.downcast_ref::<String>() {
172     ///         println!("It's a string({}): '{}'", string.len(), string);
173     ///     } else {
174     ///         println!("Not a string...");
175     ///     }
176     /// }
177     ///
178     /// print_if_string(&0);
179     /// print_if_string(&"cookie monster".to_string());
180     /// ```
181     #[stable(feature = "rust1", since = "1.0.0")]
182     #[inline]
183     pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
184         if self.is::<T>() {
185             // SAFETY: just checked whether we are pointing to the correct type
186             unsafe {
187                 Some(&*(self as *const dyn Any as *const T))
188             }
189         } else {
190             None
191         }
192     }
193
194     /// Returns some mutable reference to the boxed value if it is of type `T`, or
195     /// `None` if it isn't.
196     ///
197     /// # Examples
198     ///
199     /// ```
200     /// use std::any::Any;
201     ///
202     /// fn modify_if_u32(s: &mut dyn Any) {
203     ///     if let Some(num) = s.downcast_mut::<u32>() {
204     ///         *num = 42;
205     ///     }
206     /// }
207     ///
208     /// let mut x = 10u32;
209     /// let mut s = "starlord".to_string();
210     ///
211     /// modify_if_u32(&mut x);
212     /// modify_if_u32(&mut s);
213     ///
214     /// assert_eq!(x, 42);
215     /// assert_eq!(&s, "starlord");
216     /// ```
217     #[stable(feature = "rust1", since = "1.0.0")]
218     #[inline]
219     pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> {
220         if self.is::<T>() {
221             // SAFETY: just checked whether we are pointing to the correct type
222             unsafe {
223                 Some(&mut *(self as *mut dyn Any as *mut T))
224             }
225         } else {
226             None
227         }
228     }
229 }
230
231 impl dyn Any+Send {
232     /// Forwards to the method defined on the type `Any`.
233     ///
234     /// # Examples
235     ///
236     /// ```
237     /// use std::any::Any;
238     ///
239     /// fn is_string(s: &(dyn Any + Send)) {
240     ///     if s.is::<String>() {
241     ///         println!("It's a string!");
242     ///     } else {
243     ///         println!("Not a string...");
244     ///     }
245     /// }
246     ///
247     /// is_string(&0);
248     /// is_string(&"cookie monster".to_string());
249     /// ```
250     #[stable(feature = "rust1", since = "1.0.0")]
251     #[inline]
252     pub fn is<T: Any>(&self) -> bool {
253         Any::is::<T>(self)
254     }
255
256     /// Forwards to the method defined on the type `Any`.
257     ///
258     /// # Examples
259     ///
260     /// ```
261     /// use std::any::Any;
262     ///
263     /// fn print_if_string(s: &(dyn Any + Send)) {
264     ///     if let Some(string) = s.downcast_ref::<String>() {
265     ///         println!("It's a string({}): '{}'", string.len(), string);
266     ///     } else {
267     ///         println!("Not a string...");
268     ///     }
269     /// }
270     ///
271     /// print_if_string(&0);
272     /// print_if_string(&"cookie monster".to_string());
273     /// ```
274     #[stable(feature = "rust1", since = "1.0.0")]
275     #[inline]
276     pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
277         Any::downcast_ref::<T>(self)
278     }
279
280     /// Forwards to the method defined on the type `Any`.
281     ///
282     /// # Examples
283     ///
284     /// ```
285     /// use std::any::Any;
286     ///
287     /// fn modify_if_u32(s: &mut (dyn Any + Send)) {
288     ///     if let Some(num) = s.downcast_mut::<u32>() {
289     ///         *num = 42;
290     ///     }
291     /// }
292     ///
293     /// let mut x = 10u32;
294     /// let mut s = "starlord".to_string();
295     ///
296     /// modify_if_u32(&mut x);
297     /// modify_if_u32(&mut s);
298     ///
299     /// assert_eq!(x, 42);
300     /// assert_eq!(&s, "starlord");
301     /// ```
302     #[stable(feature = "rust1", since = "1.0.0")]
303     #[inline]
304     pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> {
305         Any::downcast_mut::<T>(self)
306     }
307 }
308
309 impl dyn Any+Send+Sync {
310     /// Forwards to the method defined on the type `Any`.
311     ///
312     /// # Examples
313     ///
314     /// ```
315     /// use std::any::Any;
316     ///
317     /// fn is_string(s: &(dyn Any + Send + Sync)) {
318     ///     if s.is::<String>() {
319     ///         println!("It's a string!");
320     ///     } else {
321     ///         println!("Not a string...");
322     ///     }
323     /// }
324     ///
325     /// is_string(&0);
326     /// is_string(&"cookie monster".to_string());
327     /// ```
328     #[stable(feature = "any_send_sync_methods", since = "1.28.0")]
329     #[inline]
330     pub fn is<T: Any>(&self) -> bool {
331         Any::is::<T>(self)
332     }
333
334     /// Forwards to the method defined on the type `Any`.
335     ///
336     /// # Examples
337     ///
338     /// ```
339     /// use std::any::Any;
340     ///
341     /// fn print_if_string(s: &(dyn Any + Send + Sync)) {
342     ///     if let Some(string) = s.downcast_ref::<String>() {
343     ///         println!("It's a string({}): '{}'", string.len(), string);
344     ///     } else {
345     ///         println!("Not a string...");
346     ///     }
347     /// }
348     ///
349     /// print_if_string(&0);
350     /// print_if_string(&"cookie monster".to_string());
351     /// ```
352     #[stable(feature = "any_send_sync_methods", since = "1.28.0")]
353     #[inline]
354     pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
355         Any::downcast_ref::<T>(self)
356     }
357
358     /// Forwards to the method defined on the type `Any`.
359     ///
360     /// # Examples
361     ///
362     /// ```
363     /// use std::any::Any;
364     ///
365     /// fn modify_if_u32(s: &mut (dyn Any + Send + Sync)) {
366     ///     if let Some(num) = s.downcast_mut::<u32>() {
367     ///         *num = 42;
368     ///     }
369     /// }
370     ///
371     /// let mut x = 10u32;
372     /// let mut s = "starlord".to_string();
373     ///
374     /// modify_if_u32(&mut x);
375     /// modify_if_u32(&mut s);
376     ///
377     /// assert_eq!(x, 42);
378     /// assert_eq!(&s, "starlord");
379     /// ```
380     #[stable(feature = "any_send_sync_methods", since = "1.28.0")]
381     #[inline]
382     pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> {
383         Any::downcast_mut::<T>(self)
384     }
385 }
386
387 ///////////////////////////////////////////////////////////////////////////////
388 // TypeID and its methods
389 ///////////////////////////////////////////////////////////////////////////////
390
391 /// A `TypeId` represents a globally unique identifier for a type.
392 ///
393 /// Each `TypeId` is an opaque object which does not allow inspection of what's
394 /// inside but does allow basic operations such as cloning, comparison,
395 /// printing, and showing.
396 ///
397 /// A `TypeId` is currently only available for types which ascribe to `'static`,
398 /// but this limitation may be removed in the future.
399 ///
400 /// While `TypeId` implements `Hash`, `PartialOrd`, and `Ord`, it is worth
401 /// noting that the hashes and ordering will vary between Rust releases. Beware
402 /// of relying on them inside of your code!
403 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
404 #[stable(feature = "rust1", since = "1.0.0")]
405 pub struct TypeId {
406     t: u64,
407 }
408
409 impl TypeId {
410     /// Returns the `TypeId` of the type this generic function has been
411     /// instantiated with.
412     ///
413     /// # Examples
414     ///
415     /// ```
416     /// use std::any::{Any, TypeId};
417     ///
418     /// fn is_string<T: ?Sized + Any>(_s: &T) -> bool {
419     ///     TypeId::of::<String>() == TypeId::of::<T>()
420     /// }
421     ///
422     /// assert_eq!(is_string(&0), false);
423     /// assert_eq!(is_string(&"cookie monster".to_string()), true);
424     /// ```
425     #[stable(feature = "rust1", since = "1.0.0")]
426     #[rustc_const_unstable(feature="const_type_id")]
427     pub const fn of<T: ?Sized + 'static>() -> TypeId {
428         TypeId {
429             #[cfg(bootstrap)]
430             // SAFETY: going away soon
431             t: unsafe { intrinsics::type_id::<T>() },
432             #[cfg(not(bootstrap))]
433             t: intrinsics::type_id::<T>(),
434         }
435     }
436 }
437
438 /// Returns the name of a type as a string slice.
439 ///
440 /// # Note
441 ///
442 /// This is intended for diagnostic use. The exact contents and format of the
443 /// string are not specified, other than being a best-effort description of the
444 /// type. For example, `type_name::<Option<String>>()` could return the
445 /// `"Option<String>"` or `"std::option::Option<std::string::String>"`, but not
446 /// `"foobar"`. In addition, the output may change between versions of the
447 /// compiler.
448 ///
449 /// The type name should not be considered a unique identifier of a type;
450 /// multiple types may share the same type name.
451 ///
452 /// The current implementation uses the same infrastructure as compiler
453 /// diagnostics and debuginfo, but this is not guaranteed.
454 ///
455 /// # Examples
456 ///
457 /// ```rust
458 /// assert_eq!(
459 ///     std::any::type_name::<Option<String>>(),
460 ///     "core::option::Option<alloc::string::String>",
461 /// );
462 /// ```
463 #[stable(feature = "type_name", since = "1.38.0")]
464 #[rustc_const_unstable(feature = "const_type_name")]
465 pub const fn type_name<T: ?Sized>() -> &'static str {
466     intrinsics::type_name::<T>()
467 }
468
469 /// Returns the name of the type of the pointed-to value as a string slice.
470 /// This is the same as `type_name::<T>()`, but can be used where the type of a
471 /// variable is not easily available.
472 ///
473 /// # Note
474 ///
475 /// This is intended for diagnostic use. The exact contents and format of the
476 /// string are not specified, other than being a best-effort description of the
477 /// type. For example, `type_name_of::<Option<String>>(None)` could return the
478 /// `"Option<String>"` or `"std::option::Option<std::string::String>"`, but not
479 /// `"foobar"`. In addition, the output may change between versions of the
480 /// compiler.
481 ///
482 /// The type name should not be considered a unique identifier of a type;
483 /// multiple types may share the same type name.
484 ///
485 /// The current implementation uses the same infrastructure as compiler
486 /// diagnostics and debuginfo, but this is not guaranteed.
487 ///
488 /// # Examples
489 ///
490 /// Prints the default integer and float types.
491 ///
492 /// ```rust
493 /// #![feature(type_name_of_val)]
494 /// use std::any::type_name_of_val;
495 ///
496 /// let x = 1;
497 /// println!("{}", type_name_of_val(&x));
498 /// let y = 1.0;
499 /// println!("{}", type_name_of_val(&y));
500 /// ```
501 #[unstable(feature = "type_name_of_val", issue = "66359")]
502 #[rustc_const_unstable(feature = "const_type_name")]
503 pub const fn type_name_of_val<T: ?Sized>(val: &T) -> &'static str {
504     let _ = val;
505     type_name::<T>()
506 }