@@ -249,6 +249,14 @@ impl<T: ?Sized> Box<T> {
249
249
/// This function is unsafe because improper use may lead to
250
250
/// memory problems. For example, a double-free may occur if the
251
251
/// function is called twice on the same raw pointer.
252
+ ///
253
+ /// # Examples
254
+ ///
255
+ /// ```
256
+ /// let x = Box::new(5);
257
+ /// let ptr = Box::into_raw(x);
258
+ /// let x = unsafe { Box::from_raw(ptr) };
259
+ /// ```
252
260
#[ stable( feature = "box_raw" , since = "1.4.0" ) ]
253
261
#[ inline]
254
262
pub unsafe fn from_raw ( raw : * mut T ) -> Self {
@@ -266,9 +274,8 @@ impl<T: ?Sized> Box<T> {
266
274
/// # Examples
267
275
///
268
276
/// ```
269
- /// let seventeen = Box::new(17);
270
- /// let raw = Box::into_raw(seventeen);
271
- /// let boxed_again = unsafe { Box::from_raw(raw) };
277
+ /// let x = Box::new(5);
278
+ /// let ptr = Box::into_raw(x);
272
279
/// ```
273
280
#[ stable( feature = "box_raw" , since = "1.4.0" ) ]
274
281
#[ inline]
@@ -399,6 +406,24 @@ impl Box<Any> {
399
406
#[ inline]
400
407
#[ stable( feature = "rust1" , since = "1.0.0" ) ]
401
408
/// Attempt to downcast the box to a concrete type.
409
+ ///
410
+ /// # Examples
411
+ ///
412
+ /// ```
413
+ /// use std::any::Any;
414
+ ///
415
+ /// fn print_if_string(value: Box<Any>) {
416
+ /// if let Ok(string) = value.downcast::<String>() {
417
+ /// println!("String ({}): {}", string.len(), string);
418
+ /// }
419
+ /// }
420
+ ///
421
+ /// fn main() {
422
+ /// let my_string = "Hello World".to_string();
423
+ /// print_if_string(Box::new(my_string));
424
+ /// print_if_string(Box::new(0i8));
425
+ /// }
426
+ /// ```
402
427
pub fn downcast < T : Any > ( self ) -> Result < Box < T > , Box < Any > > {
403
428
if self . is :: < T > ( ) {
404
429
unsafe {
@@ -419,6 +444,24 @@ impl Box<Any + Send> {
419
444
#[ inline]
420
445
#[ stable( feature = "rust1" , since = "1.0.0" ) ]
421
446
/// Attempt to downcast the box to a concrete type.
447
+ ///
448
+ /// # Examples
449
+ ///
450
+ /// ```
451
+ /// use std::any::Any;
452
+ ///
453
+ /// fn print_if_string(value: Box<Any + Send>) {
454
+ /// if let Ok(string) = value.downcast::<String>() {
455
+ /// println!("String ({}): {}", string.len(), string);
456
+ /// }
457
+ /// }
458
+ ///
459
+ /// fn main() {
460
+ /// let my_string = "Hello World".to_string();
461
+ /// print_if_string(Box::new(my_string));
462
+ /// print_if_string(Box::new(0i8));
463
+ /// }
464
+ /// ```
422
465
pub fn downcast < T : Any > ( self ) -> Result < Box < T > , Box < Any + Send > > {
423
466
<Box < Any > >:: downcast ( self ) . map_err ( |s| unsafe {
424
467
// reapply the Send marker
0 commit comments