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