From 1ef7bdc0c7a3ad8a4b3421b3224988cbd0b1a557 Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Sat, 9 Jul 2016 19:57:08 +0200 Subject: [PATCH] Improve boxed docs --- src/liballoc/boxed.rs | 49 ++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 46 insertions(+), 3 deletions(-) diff --git a/src/liballoc/boxed.rs b/src/liballoc/boxed.rs index 51523ca8dc6..7ba5ca30941 100644 --- a/src/liballoc/boxed.rs +++ b/src/liballoc/boxed.rs @@ -249,6 +249,14 @@ impl Box { /// This function is unsafe because improper use may lead to /// memory problems. For example, a double-free may occur if the /// function is called twice on the same raw pointer. + /// + /// # Examples + /// + /// ``` + /// let x = Box::new(5); + /// let ptr = Box::into_raw(x); + /// let x = unsafe { Box::from_raw(ptr) }; + /// ``` #[stable(feature = "box_raw", since = "1.4.0")] #[inline] pub unsafe fn from_raw(raw: *mut T) -> Self { @@ -266,9 +274,8 @@ impl Box { /// # Examples /// /// ``` - /// let seventeen = Box::new(17); - /// let raw = Box::into_raw(seventeen); - /// let boxed_again = unsafe { Box::from_raw(raw) }; + /// let x = Box::new(5); + /// let ptr = Box::into_raw(x); /// ``` #[stable(feature = "box_raw", since = "1.4.0")] #[inline] @@ -399,6 +406,24 @@ impl Box { #[inline] #[stable(feature = "rust1", since = "1.0.0")] /// Attempt to downcast the box to a concrete type. + /// + /// # Examples + /// + /// ``` + /// use std::any::Any; + /// + /// fn print_if_string(value: Box) { + /// if let Ok(string) = value.downcast::() { + /// println!("String ({}): {}", string.len(), string); + /// } + /// } + /// + /// fn main() { + /// let my_string = "Hello World".to_string(); + /// print_if_string(Box::new(my_string)); + /// print_if_string(Box::new(0i8)); + /// } + /// ``` pub fn downcast(self) -> Result, Box> { if self.is::() { unsafe { @@ -419,6 +444,24 @@ impl Box { #[inline] #[stable(feature = "rust1", since = "1.0.0")] /// Attempt to downcast the box to a concrete type. + /// + /// # Examples + /// + /// ``` + /// use std::any::Any; + /// + /// fn print_if_string(value: Box) { + /// if let Ok(string) = value.downcast::() { + /// println!("String ({}): {}", string.len(), string); + /// } + /// } + /// + /// fn main() { + /// let my_string = "Hello World".to_string(); + /// print_if_string(Box::new(my_string)); + /// print_if_string(Box::new(0i8)); + /// } + /// ``` pub fn downcast(self) -> Result, Box> { >::downcast(self).map_err(|s| unsafe { // reapply the Send marker