diff --git a/src/doc/book/closures.md b/src/doc/book/closures.md index e8c88b7db06..666d0946ecc 100644 --- a/src/doc/book/closures.md +++ b/src/doc/book/closures.md @@ -336,7 +336,7 @@ could annotate it on the function declaration: ```rust,ignore fn call_with_ref<'a, F>(some_closure:F) -> i32 - where F: Fn(&'a 32) -> i32 { + where F: Fn(&'a i32) -> i32 { ``` However this presents a problem with in our case. When you specify the explicit @@ -350,7 +350,7 @@ of the closure we can use Higher-Ranked Trait Bounds with the `for<...>` syntax: ```ignore fn call_with_ref(some_closure:F) -> i32 - where F: for<'a> Fn(&'a 32) -> i32 { + where F: for<'a> Fn(&'a i32) -> i32 { ``` This lets the Rust compiler find the minimum lifetime to invoke our closure and diff --git a/src/doc/reference.md b/src/doc/reference.md index 59dbffd6e28..b3073f5e526 100644 --- a/src/doc/reference.md +++ b/src/doc/reference.md @@ -2633,7 +2633,7 @@ comma: There are several forms of struct expressions. A _struct expression_ consists of the [path](#paths) of a [struct item](#structs), followed by -a brace-enclosed list of one or more comma-separated name-value pairs, +a brace-enclosed list of zero or more comma-separated name-value pairs, providing the field values of a new instance of the struct. A field name can be any identifier, and is separated from its value expression by a colon. The location denoted by a struct field is mutable if and only if the @@ -2652,10 +2652,12 @@ The following are examples of struct expressions: ``` # struct Point { x: f64, y: f64 } +# struct NothingInMe { } # struct TuplePoint(f64, f64); # mod game { pub struct User<'a> { pub name: &'a str, pub age: u32, pub score: usize } } # struct Cookie; fn some_fn(t: T) {} Point {x: 10.0, y: 20.0}; +NothingInMe {}; TuplePoint(10.0, 20.0); let u = game::User {name: "Joe", age: 35, score: 100_000}; some_fn::(Cookie); 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 diff --git a/src/libcore/any.rs b/src/libcore/any.rs index 49304b1f3bf..a452be2565b 100644 --- a/src/libcore/any.rs +++ b/src/libcore/any.rs @@ -92,6 +92,23 @@ use marker::{Reflect, Sized}; #[stable(feature = "rust1", since = "1.0.0")] pub trait Any: Reflect + 'static { /// Gets the `TypeId` of `self`. + /// + /// # Examples + /// + /// ``` + /// #![feature(get_type_id)] + /// + /// use std::any::{Any, TypeId}; + /// + /// fn is_string(s: &Any) -> bool { + /// TypeId::of::() == s.get_type_id() + /// } + /// + /// fn main() { + /// assert_eq!(is_string(&0), false); + /// assert_eq!(is_string(&"cookie monster".to_owned()), true); + /// } + /// ``` #[unstable(feature = "get_type_id", reason = "this method will likely be replaced by an associated static", issue = "27745")] @@ -125,7 +142,26 @@ impl fmt::Debug for Any + Send { } impl Any { - /// Returns true if the boxed type is the same as `T` + /// Returns true if the boxed type is the same as `T`. + /// + /// # Examples + /// + /// ``` + /// use std::any::Any; + /// + /// fn is_string(s: &Any) { + /// if s.is::() { + /// println!("It's a string!"); + /// } else { + /// println!("Not a string..."); + /// } + /// } + /// + /// fn main() { + /// is_string(&0); + /// is_string(&"cookie monster".to_owned()); + /// } + /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn is(&self) -> bool { @@ -141,6 +177,25 @@ impl Any { /// Returns some reference to the boxed value if it is of type `T`, or /// `None` if it isn't. + /// + /// # Examples + /// + /// ``` + /// use std::any::Any; + /// + /// fn print_if_string(s: &Any) { + /// if let Some(string) = s.downcast_ref::() { + /// println!("It's a string({}): '{}'", string.len(), string); + /// } else { + /// println!("Not a string..."); + /// } + /// } + /// + /// fn main() { + /// print_if_string(&0); + /// print_if_string(&"cookie monster".to_owned()); + /// } + /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn downcast_ref(&self) -> Option<&T> { @@ -159,6 +214,29 @@ impl Any { /// Returns some mutable reference to the boxed value if it is of type `T`, or /// `None` if it isn't. + /// + /// # Examples + /// + /// ``` + /// use std::any::Any; + /// + /// fn modify_if_u32(s: &mut Any) { + /// if let Some(num) = s.downcast_mut::() { + /// *num = 42; + /// } + /// } + /// + /// fn main() { + /// let mut x = 10u32; + /// let mut s = "starlord".to_owned(); + /// + /// modify_if_u32(&mut x); + /// modify_if_u32(&mut s); + /// + /// assert_eq!(x, 42); + /// assert_eq!(&s, "starlord"); + /// } + /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn downcast_mut(&mut self) -> Option<&mut T> { @@ -178,6 +256,25 @@ impl Any { impl Any+Send { /// Forwards to the method defined on the type `Any`. + /// + /// # Examples + /// + /// ``` + /// use std::any::Any; + /// + /// fn is_string(s: &(Any + Send)) { + /// if s.is::() { + /// println!("It's a string!"); + /// } else { + /// println!("Not a string..."); + /// } + /// } + /// + /// fn main() { + /// is_string(&0); + /// is_string(&"cookie monster".to_owned()); + /// } + /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn is(&self) -> bool { @@ -185,6 +282,25 @@ impl Any+Send { } /// Forwards to the method defined on the type `Any`. + /// + /// # Examples + /// + /// ``` + /// use std::any::Any; + /// + /// fn print_if_string(s: &(Any + Send)) { + /// if let Some(string) = s.downcast_ref::() { + /// println!("It's a string({}): '{}'", string.len(), string); + /// } else { + /// println!("Not a string..."); + /// } + /// } + /// + /// fn main() { + /// print_if_string(&0); + /// print_if_string(&"cookie monster".to_owned()); + /// } + /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn downcast_ref(&self) -> Option<&T> { @@ -192,6 +308,29 @@ impl Any+Send { } /// Forwards to the method defined on the type `Any`. + /// + /// # Examples + /// + /// ``` + /// use std::any::Any; + /// + /// fn modify_if_u32(s: &mut (Any+ Send)) { + /// if let Some(num) = s.downcast_mut::() { + /// *num = 42; + /// } + /// } + /// + /// fn main() { + /// let mut x = 10u32; + /// let mut s = "starlord".to_owned(); + /// + /// modify_if_u32(&mut x); + /// modify_if_u32(&mut s); + /// + /// assert_eq!(x, 42); + /// assert_eq!(&s, "starlord"); + /// } + /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn downcast_mut(&mut self) -> Option<&mut T> { @@ -220,7 +359,24 @@ pub struct TypeId { impl TypeId { /// Returns the `TypeId` of the type this generic function has been - /// instantiated with + /// instantiated with. + /// + /// # Examples + /// + /// ``` + /// #![feature(get_type_id)] + /// + /// use std::any::{Any, TypeId}; + /// + /// fn is_string(s: &Any) -> bool { + /// TypeId::of::() == s.get_type_id() + /// } + /// + /// fn main() { + /// assert_eq!(is_string(&0), false); + /// assert_eq!(is_string(&"cookie monster".to_owned()), true); + /// } + /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn of() -> TypeId { TypeId { diff --git a/src/libcore/cell.rs b/src/libcore/cell.rs index 9435be3b012..65cb1aaaff6 100644 --- a/src/libcore/cell.rs +++ b/src/libcore/cell.rs @@ -237,6 +237,17 @@ impl Cell { /// /// This call borrows `Cell` mutably (at compile-time) which guarantees /// that we possess the only reference. + /// + /// # Examples + /// + /// ``` + /// use std::cell::Cell; + /// + /// let mut c = Cell::new(5); + /// *c.get_mut() += 1; + /// + /// assert_eq!(c.get(), 6); + /// ``` #[inline] #[stable(feature = "cell_get_mut", since = "1.11.0")] pub fn get_mut(&mut self) -> &mut T { @@ -388,6 +399,22 @@ impl RefCell { /// /// The returned value can be dispatched on to determine if a call to /// `borrow` or `borrow_mut` would succeed. + /// + /// # Examples + /// + /// ``` + /// #![feature(borrow_state)] + /// + /// use std::cell::{BorrowState, RefCell}; + /// + /// let c = RefCell::new(5); + /// + /// match c.borrow_state() { + /// BorrowState::Writing => println!("Cannot be borrowed"), + /// BorrowState::Reading => println!("Cannot be borrowed mutably"), + /// BorrowState::Unused => println!("Can be borrowed (mutably as well)"), + /// } + /// ``` #[unstable(feature = "borrow_state", issue = "27733")] #[inline] pub fn borrow_state(&self) -> BorrowState { @@ -498,6 +525,17 @@ impl RefCell { /// This can be used to circumvent `RefCell`'s safety checks. /// /// This function is `unsafe` because `UnsafeCell`'s field is public. + /// + /// # Examples + /// + /// ``` + /// #![feature(as_unsafe_cell)] + /// + /// use std::cell::RefCell; + /// + /// let c = RefCell::new(5); + /// let c = unsafe { c.as_unsafe_cell() }; + /// ``` #[inline] #[unstable(feature = "as_unsafe_cell", issue = "27708")] pub unsafe fn as_unsafe_cell(&self) -> &UnsafeCell { @@ -508,6 +546,17 @@ impl RefCell { /// /// This call borrows `RefCell` mutably (at compile-time) so there is no /// need for dynamic checks. + /// + /// # Examples + /// + /// ``` + /// use std::cell::RefCell; + /// + /// let mut c = RefCell::new(5); + /// *c.get_mut() += 1; + /// + /// assert_eq!(c, RefCell::new(6)); + /// ``` #[inline] #[stable(feature = "cell_get_mut", since = "1.11.0")] pub fn get_mut(&mut self) -> &mut T { diff --git a/src/libstd/error.rs b/src/libstd/error.rs index 2a2d41112ff..1459420cdc0 100644 --- a/src/libstd/error.rs +++ b/src/libstd/error.rs @@ -66,10 +66,80 @@ pub trait Error: Debug + Display + Reflect { /// The description should not contain newlines or sentence-ending /// punctuation, to facilitate embedding in larger user-facing /// strings. + /// + /// # Examples + /// + /// ``` + /// use std::error::Error; + /// + /// match "xc".parse::() { + /// Err(e) => { + /// println!("Error: {}", e.description()); + /// } + /// _ => println!("No error"), + /// } + /// ``` #[stable(feature = "rust1", since = "1.0.0")] fn description(&self) -> &str; /// The lower-level cause of this error, if any. + /// + /// # Examples + /// + /// ``` + /// use std::error::Error; + /// use std::fmt; + /// + /// #[derive(Debug)] + /// struct SuperError { + /// side: SuperErrorSideKick, + /// } + /// + /// impl fmt::Display for SuperError { + /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + /// write!(f, "SuperError is here!") + /// } + /// } + /// + /// impl Error for SuperError { + /// fn description(&self) -> &str { + /// "I'm the superhero of errors!" + /// } + /// + /// fn cause(&self) -> Option<&Error> { + /// Some(&self.side) + /// } + /// } + /// + /// #[derive(Debug)] + /// struct SuperErrorSideKick; + /// + /// impl fmt::Display for SuperErrorSideKick { + /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + /// write!(f, "SuperErrorSideKick is here!") + /// } + /// } + /// + /// impl Error for SuperErrorSideKick { + /// fn description(&self) -> &str { + /// "I'm SuperError side kick!" + /// } + /// } + /// + /// fn get_super_error() -> Result<(), SuperError> { + /// Err(SuperError { side: SuperErrorSideKick }) + /// } + /// + /// fn main() { + /// match get_super_error() { + /// Err(e) => { + /// println!("Error: {}", e.description()); + /// println!("Caused by: {}", e.cause().unwrap()); + /// } + /// _ => println!("No error"), + /// } + /// } + /// ``` #[stable(feature = "rust1", since = "1.0.0")] fn cause(&self) -> Option<&Error> { None } diff --git a/src/libstd/process.rs b/src/libstd/process.rs index 2edd1a30638..16bc81de78e 100644 --- a/src/libstd/process.rs +++ b/src/libstd/process.rs @@ -27,8 +27,9 @@ use sys_common::{AsInner, AsInnerMut, FromInner, IntoInner}; /// Representation of a running or exited child process. /// /// This structure is used to represent and manage child processes. A child -/// process is created via the `Command` struct, which configures the spawning -/// process and can itself be constructed using a builder-style interface. +/// process is created via the [`Command`] struct, which configures the +/// spawning process and can itself be constructed using a builder-style +/// interface. /// /// # Examples /// @@ -48,13 +49,18 @@ use sys_common::{AsInner, AsInnerMut, FromInner, IntoInner}; /// /// # Note /// -/// Take note that there is no implementation of -/// [`Drop`](../../core/ops/trait.Drop.html) for child processes, so if you -/// do not ensure the `Child` has exited then it will continue to run, even -/// after the `Child` handle to the child process has gone out of scope. +/// Take note that there is no implementation of [`Drop`] for child processes, +/// so if you do not ensure the `Child` has exited then it will continue to +/// run, even after the `Child` handle to the child process has gone out of +/// scope. /// -/// Calling `wait` (or other functions that wrap around it) will make the -/// parent process wait until the child has actually exited before continuing. +/// Calling [`wait`][`wait`] (or other functions that wrap around it) will make +/// the parent process wait until the child has actually exited before +/// continuing. +/// +/// [`Command`]: struct.Command.html +/// [`Drop`]: ../../core/ops/trait.Drop.html +/// [`wait`]: #method.wait #[stable(feature = "process", since = "1.0.0")] pub struct Child { handle: imp::Process, @@ -91,7 +97,11 @@ impl IntoInner for Child { fn into_inner(self) -> imp::Process { self.handle } } -/// A handle to a child process's stdin +/// A handle to a child process's stdin. This struct is used in the [`stdin`] +/// field on [`Child`]. +/// +/// [`Child`]: struct.Child.html +/// [`stdin`]: struct.Child.html#structfield.stdin #[stable(feature = "process", since = "1.0.0")] pub struct ChildStdin { inner: AnonPipe @@ -122,7 +132,11 @@ impl FromInner for ChildStdin { } } -/// A handle to a child process's stdout +/// A handle to a child process's stdout. This struct is used in the [`stdout`] +/// field on [`Child`]. +/// +/// [`Child`]: struct.Child.html +/// [`stdout`]: struct.Child.html#structfield.stdout #[stable(feature = "process", since = "1.0.0")] pub struct ChildStdout { inner: AnonPipe @@ -152,7 +166,11 @@ impl FromInner for ChildStdout { } } -/// A handle to a child process's stderr +/// A handle to a child process's stderr. This struct is used in the [`stderr`] +/// field on [`Child`]. +/// +/// [`Child`]: struct.Child.html +/// [`stderr`]: struct.Child.html#structfield.stderr #[stable(feature = "process", since = "1.0.0")] pub struct ChildStderr { inner: AnonPipe