File tree Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Original file line number Diff line number Diff line change @@ -1372,6 +1372,39 @@ impl<A: Allocator> Box<dyn Any + Send, A> {
13721372 }
13731373}
13741374
1375+ impl < A : Allocator > Box < dyn Any + Send + Sync , A > {
1376+ #[ inline]
1377+ #[ stable( feature = "box_send_sync_any_downcast" , since = "1.51.0" ) ]
1378+ /// Attempt to downcast the box to a concrete type.
1379+ ///
1380+ /// # Examples
1381+ ///
1382+ /// ```
1383+ /// use std::any::Any;
1384+ ///
1385+ /// fn print_if_string(value: Box<dyn Any + Send + Sync>) {
1386+ /// if let Ok(string) = value.downcast::<String>() {
1387+ /// println!("String ({}): {}", string.len(), string);
1388+ /// }
1389+ /// }
1390+ ///
1391+ /// let my_string = "Hello World".to_string();
1392+ /// print_if_string(Box::new(my_string));
1393+ /// print_if_string(Box::new(0i8));
1394+ /// ```
1395+ pub fn downcast < T : Any > ( self ) -> Result < Box < T , A > , Self > {
1396+ if self . is :: < T > ( ) {
1397+ unsafe {
1398+ let ( raw, alloc) : ( * mut ( dyn Any + Send + Sync ) , _ ) =
1399+ Box :: into_raw_with_allocator ( self ) ;
1400+ Ok ( Box :: from_raw_in ( raw as * mut T , alloc) )
1401+ }
1402+ } else {
1403+ Err ( self )
1404+ }
1405+ }
1406+ }
1407+
13751408#[ stable( feature = "rust1" , since = "1.0.0" ) ]
13761409impl < T : fmt:: Display + ?Sized , A : Allocator > fmt:: Display for Box < T , A > {
13771410 fn fmt ( & self , f : & mut fmt:: Formatter < ' _ > ) -> fmt:: Result {
You can’t perform that action at this time.
0 commit comments