From 422cf2d34a1ec50a66ac71fd1f68ccf3ce0e38fb Mon Sep 17 00:00:00 2001 From: Andrew Barchuk Date: Sun, 7 Feb 2016 23:00:01 +0200 Subject: [PATCH 1/6] Clean up Error Handling case study examples Remove unnecessary cloning and conversions. Expand tabs left in examples. --- src/doc/book/error-handling.md | 89 +++++++++++++++++----------------- 1 file changed, 44 insertions(+), 45 deletions(-) diff --git a/src/doc/book/error-handling.md b/src/doc/book/error-handling.md index 73875704ecaf7..affea7926a2f9 100644 --- a/src/doc/book/error-handling.md +++ b/src/doc/book/error-handling.md @@ -1592,7 +1592,7 @@ fn print_usage(program: &str, opts: Options) { fn main() { let args: Vec = env::args().collect(); - let program = args[0].clone(); + let program = &args[0]; let mut opts = Options::new(); opts.optflag("h", "help", "Show this usage message."); @@ -1605,10 +1605,10 @@ fn main() { print_usage(&program, opts); return; } - let data_path = args[1].clone(); - let city = args[2].clone(); + let data_path = &args[1]; + let city = &args[2]; - // Do stuff with information + // Do stuff with information } ``` @@ -1640,7 +1640,6 @@ sure to add `extern crate csv;` to the top of your file.) ```rust,ignore use std::fs::File; -use std::path::Path; // This struct represents the data in each row of the CSV file. // Type based decoding absolves us of a lot of the nitty gritty error @@ -1666,7 +1665,7 @@ fn print_usage(program: &str, opts: Options) { fn main() { let args: Vec = env::args().collect(); - let program = args[0].clone(); + let program = &args[0]; let mut opts = Options::new(); opts.optflag("h", "help", "Show this usage message."); @@ -1678,25 +1677,24 @@ fn main() { if matches.opt_present("h") { print_usage(&program, opts); - return; - } + return; + } - let data_file = args[1].clone(); - let data_path = Path::new(&data_file); - let city = args[2].clone(); + let data_path = &args[1]; + let city: &str = &args[2]; - let file = File::open(data_path).unwrap(); - let mut rdr = csv::Reader::from_reader(file); + let file = File::open(data_path).unwrap(); + let mut rdr = csv::Reader::from_reader(file); - for row in rdr.decode::() { - let row = row.unwrap(); + for row in rdr.decode::() { + let row = row.unwrap(); - if row.city == city { - println!("{}, {}: {:?}", - row.city, row.country, - row.population.expect("population count")); - } - } + if row.city == city { + println!("{}, {}: {:?}", + row.city, row.country, + row.population.expect("population count")); + } + } } ``` @@ -1745,6 +1743,8 @@ Note that we opt to handle the possibility of a missing population count by simply ignoring that row. ```rust,ignore +use std::path::Path; + struct Row { // unchanged } @@ -1782,27 +1782,26 @@ fn search>(file_path: P, city: &str) -> Vec { } fn main() { - let args: Vec = env::args().collect(); - let program = args[0].clone(); + let args: Vec = env::args().collect(); + let program = &args[0]; - let mut opts = Options::new(); - opts.optflag("h", "help", "Show this usage message."); + let mut opts = Options::new(); + opts.optflag("h", "help", "Show this usage message."); - let matches = match opts.parse(&args[1..]) { - Ok(m) => { m } - Err(e) => { panic!(e.to_string()) } - }; - if matches.opt_present("h") { - print_usage(&program, opts); - return; - } + let matches = match opts.parse(&args[1..]) { + Ok(m) => { m } + Err(e) => { panic!(e.to_string()) } + }; + if matches.opt_present("h") { + print_usage(&program, opts); + return; + } - let data_file = args[1].clone(); - let data_path = Path::new(&data_file); - let city = args[2].clone(); - for pop in search(&data_path, &city) { - println!("{}, {}: {:?}", pop.city, pop.country, pop.count); - } + let data_path = &args[1]; + let city = &args[2]; + for pop in search(data_path, city) { + println!("{}, {}: {:?}", pop.city, pop.country, pop.count); + } } ``` @@ -1912,7 +1911,7 @@ First, here's the new usage: ```rust,ignore fn print_usage(program: &str, opts: Options) { - println!("{}", opts.usage(&format!("Usage: {} [options] ", program))); + println!("{}", opts.usage(&format!("Usage: {} [options] ", program))); } ``` The next part is going to be only a little harder: @@ -1924,16 +1923,16 @@ opts.optopt("f", "file", "Choose an input file, instead of using STDIN.", "NAME" opts.optflag("h", "help", "Show this usage message."); ... let file = matches.opt_str("f"); -let data_file = file.as_ref().map(Path::new); +let data_file = &file.as_ref().map(Path::new); let city = if !matches.free.is_empty() { - matches.free[0].clone() + &matches.free[0] } else { - print_usage(&program, opts); - return; + print_usage(&program, opts); + return; }; -match search(&data_file, &city) { +match search(data_file, city) { Ok(pops) => { for pop in pops { println!("{}, {}: {:?}", pop.city, pop.country, pop.count); From 5c3a1940343729bb4b9e80d6eeb93274af9baf52 Mon Sep 17 00:00:00 2001 From: Scott Whittaker Date: Tue, 9 Feb 2016 11:47:42 -0500 Subject: [PATCH 2/6] mod.rs: fix typo "particularly" was misspelled. --- src/libstd/prelude/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/libstd/prelude/mod.rs b/src/libstd/prelude/mod.rs index e04a676b81250..a0db471deceb3 100644 --- a/src/libstd/prelude/mod.rs +++ b/src/libstd/prelude/mod.rs @@ -17,7 +17,7 @@ //! //! The *prelude* is the list of things that Rust automatically imports into //! every Rust program. It's kept as small as possible, and is focused on -//! things, particuarly traits, which are used in almost every single Rust +//! things, particularly traits, which are used in almost every single Rust //! program. //! //! On a technical level, Rust inserts From 02aa0aff2f0b42368dd871186510493fa60d785a Mon Sep 17 00:00:00 2001 From: "Carlos E. Garcia" Date: Tue, 9 Feb 2016 11:52:39 -0500 Subject: [PATCH 3/6] Minor spelling fixes --- src/doc/book/error-handling.md | 2 +- src/libbacktrace/ansidecl.h | 2 +- src/libcollections/btree/node.rs | 2 +- src/libcollections/str.rs | 2 +- src/libcollections/string.rs | 2 +- src/libcore/convert.rs | 2 +- src/libcore/str/mod.rs | 2 +- src/librbml/lib.rs | 2 +- src/librustc/middle/pat_util.rs | 4 ++-- src/librustc/middle/ty/mod.rs | 2 +- src/librustc/mir/visit.rs | 2 +- src/librustc_trans/trans/common.rs | 2 +- src/librustc_typeck/check/mod.rs | 2 +- src/libstd/fs.rs | 2 +- src/libstd/memchr.rs | 2 +- src/libstd/panic.rs | 2 +- src/test/compile-fail/issue-30438-c.rs | 2 +- .../traits-inductive-overflow-supertrait-oibit.rs | 2 +- src/test/run-pass/mir_trans_calls.rs | 2 +- 19 files changed, 20 insertions(+), 20 deletions(-) diff --git a/src/doc/book/error-handling.md b/src/doc/book/error-handling.md index 73875704ecaf7..ca871a264a0e8 100644 --- a/src/doc/book/error-handling.md +++ b/src/doc/book/error-handling.md @@ -265,7 +265,7 @@ fn map(option: Option, f: F) -> Option where F: FnOnce(T) -> A { ``` Indeed, `map` is [defined as a method][2] on `Option` in the standard library. -As a method, it has a slighly different signature: methods take `self`, `&self`, +As a method, it has a slightly different signature: methods take `self`, `&self`, or `&mut self` as their first argument. Armed with our new combinator, we can rewrite our `extension_explicit` method diff --git a/src/libbacktrace/ansidecl.h b/src/libbacktrace/ansidecl.h index 6e4bfc21f25fb..4087dd7291750 100644 --- a/src/libbacktrace/ansidecl.h +++ b/src/libbacktrace/ansidecl.h @@ -1,4 +1,4 @@ -/* ANSI and traditional C compatability macros +/* ANSI and traditional C compatibility macros Copyright (C) 1991-2015 Free Software Foundation, Inc. This file is part of the GNU C Library. diff --git a/src/libcollections/btree/node.rs b/src/libcollections/btree/node.rs index f07962811fdab..8ae23a646e488 100644 --- a/src/libcollections/btree/node.rs +++ b/src/libcollections/btree/node.rs @@ -28,7 +28,7 @@ // } // ``` // -// Since Rust doesn't acutally have dependent types and polymorphic recursion, +// Since Rust doesn't actually have dependent types and polymorphic recursion, // we make do with lots of unsafety. use alloc::heap; diff --git a/src/libcollections/str.rs b/src/libcollections/str.rs index 20a7c651350cb..89b5e5b30755c 100644 --- a/src/libcollections/str.rs +++ b/src/libcollections/str.rs @@ -1808,7 +1808,7 @@ impl str { // Σ maps to σ, except at the end of a word where it maps to ς. // This is the only conditional (contextual) but language-independent mapping // in `SpecialCasing.txt`, - // so hard-code it rather than have a generic "condition" mechanim. + // so hard-code it rather than have a generic "condition" mechanism. // See https://github.com/rust-lang/rust/issues/26035 map_uppercase_sigma(self, i, &mut s) } else { diff --git a/src/libcollections/string.rs b/src/libcollections/string.rs index 7f6def6832047..7137fdde97e2f 100644 --- a/src/libcollections/string.rs +++ b/src/libcollections/string.rs @@ -193,7 +193,7 @@ use boxed::Box; /// mem::forget(story); /// /// // We can re-build a String out of ptr, len, and capacity. This is all -/// // unsafe becuase we are responsible for making sure the components are +/// // unsafe because we are responsible for making sure the components are /// // valid: /// let s = unsafe { String::from_raw_parts(ptr as *mut _, len, capacity) } ; /// diff --git a/src/libcore/convert.rs b/src/libcore/convert.rs index c207ad16595d1..b4ac020795c38 100644 --- a/src/libcore/convert.rs +++ b/src/libcore/convert.rs @@ -19,7 +19,7 @@ //! //! - Impl the `As*` traits for reference-to-reference conversions //! - Impl the `Into` trait when you want to consume the value in the conversion -//! - The `From` trait is the most flexible, usefull for values _and_ references conversions +//! - The `From` trait is the most flexible, useful for values _and_ references conversions //! //! As a library writer, you should prefer implementing `From` rather than //! `Into`, as `From` provides greater flexibility and offer the equivalent `Into` diff --git a/src/libcore/str/mod.rs b/src/libcore/str/mod.rs index f19970546d79b..fa169416a1081 100644 --- a/src/libcore/str/mod.rs +++ b/src/libcore/str/mod.rs @@ -1740,7 +1740,7 @@ impl StrExt for str { let mut matcher = pat.into_searcher(self); if let Some((a, b)) = matcher.next_reject() { i = a; - j = b; // Rember earliest known match, correct it below if + j = b; // Remember earliest known match, correct it below if // last match is different } if let Some((_, b)) = matcher.next_reject_back() { diff --git a/src/librbml/lib.rs b/src/librbml/lib.rs index 8404026df143e..1727fa2a0d34a 100644 --- a/src/librbml/lib.rs +++ b/src/librbml/lib.rs @@ -107,7 +107,7 @@ //! //! - `Opaque` (`17`): An opaque, custom-format tag. //! Used to wrap ordinary custom tags or data in the auto-serialized context. -//! Rustc typically uses this to encode type informations. +//! Rustc typically uses this to encode type information. //! //! First 0x20 tags are reserved by RBML; custom tags start at 0x20. diff --git a/src/librustc/middle/pat_util.rs b/src/librustc/middle/pat_util.rs index 41367b9361fbb..8181e7d798c12 100644 --- a/src/librustc/middle/pat_util.rs +++ b/src/librustc/middle/pat_util.rs @@ -153,7 +153,7 @@ pub fn pat_contains_bindings(dm: &DefMap, pat: &hir::Pat) -> bool { } /// Checks if the pattern contains any `ref` or `ref mut` bindings, -/// and if yes wether its containing mutable ones or just immutables ones. +/// and if yes whether its containing mutable ones or just immutables ones. pub fn pat_contains_ref_binding(dm: &RefCell, pat: &hir::Pat) -> Option { let mut result = None; pat_bindings(dm, pat, |mode, _, _, _| { @@ -172,7 +172,7 @@ pub fn pat_contains_ref_binding(dm: &RefCell, pat: &hir::Pat) -> Option< } /// Checks if the patterns for this arm contain any `ref` or `ref mut` -/// bindings, and if yes wether its containing mutable ones or just immutables ones. +/// bindings, and if yes whether its containing mutable ones or just immutables ones. pub fn arm_contains_ref_binding(dm: &RefCell, arm: &hir::Arm) -> Option { arm.pats.iter() .filter_map(|pat| pat_contains_ref_binding(dm, pat)) diff --git a/src/librustc/middle/ty/mod.rs b/src/librustc/middle/ty/mod.rs index 3a57474c30322..e3357aabd5dd5 100644 --- a/src/librustc/middle/ty/mod.rs +++ b/src/librustc/middle/ty/mod.rs @@ -2236,7 +2236,7 @@ impl<'tcx> ctxt<'tcx> { /// Given the did of an ADT, return a reference to its definition. pub fn lookup_adt_def(&self, did: DefId) -> AdtDef<'tcx> { // when reverse-variance goes away, a transmute:: - // woud be needed here. + // would be needed here. self.lookup_adt_def_master(did) } diff --git a/src/librustc/mir/visit.rs b/src/librustc/mir/visit.rs index fb4e0e97054b9..5e3c6e028a325 100644 --- a/src/librustc/mir/visit.rs +++ b/src/librustc/mir/visit.rs @@ -92,7 +92,7 @@ macro_rules! make_mir_visitor { } // The `super_xxx` methods comprise the default behavior and are - // not meant to be overidden. + // not meant to be overridden. fn super_mir(&mut self, mir: & $($mutability)* Mir<'tcx>) { diff --git a/src/librustc_trans/trans/common.rs b/src/librustc_trans/trans/common.rs index ec33046e5d914..1269c266c7c10 100644 --- a/src/librustc_trans/trans/common.rs +++ b/src/librustc_trans/trans/common.rs @@ -541,7 +541,7 @@ impl<'a, 'tcx> FunctionContext<'a, 'tcx> { } // Returns a ValueRef of the "eh_unwind_resume" lang item if one is defined, - // otherwise declares it as an external funtion. + // otherwise declares it as an external function. pub fn eh_unwind_resume(&self) -> ValueRef { use trans::attributes; assert!(self.ccx.sess().target.target.options.custom_unwind_resume); diff --git a/src/librustc_typeck/check/mod.rs b/src/librustc_typeck/check/mod.rs index 9a0d6bc16411a..a476f9e1a8060 100644 --- a/src/librustc_typeck/check/mod.rs +++ b/src/librustc_typeck/check/mod.rs @@ -1809,7 +1809,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { debug!("select_all_obligations_and_apply_defaults: defaults={:?}", default_map); // We loop over the unsolved variables, resolving them and if they are - // and unconstrainted numberic type we add them to the set of unbound + // and unconstrainted numeric type we add them to the set of unbound // variables. We do this so we only apply literal fallback to type // variables without defaults. for ty in &unsolved_variables { diff --git a/src/libstd/fs.rs b/src/libstd/fs.rs index 2087148d84477..d42b948918049 100644 --- a/src/libstd/fs.rs +++ b/src/libstd/fs.rs @@ -521,7 +521,7 @@ impl OpenOptions { /// No file is allowed to exist at the target location, also no (dangling) /// symlink. /// - /// This option is usefull because it as atomic. Otherwise between checking + /// This option is useful because it as atomic. Otherwise between checking /// whether a file exists and creating a new one, the file may have been /// created by another process (a TOCTOU race condition / attack). /// diff --git a/src/libstd/memchr.rs b/src/libstd/memchr.rs index 27702e2e59aef..1d97611eabb26 100644 --- a/src/libstd/memchr.rs +++ b/src/libstd/memchr.rs @@ -150,7 +150,7 @@ mod fallback { // Scan for a single byte value by reading two `usize` words at a time. // // Split `text` in three parts - // - unaligned inital part, before the first word aligned address in text + // - unaligned initial part, before the first word aligned address in text // - body, scan by 2 words at a time // - the last remaining part, < 2 word size let len = text.len(); diff --git a/src/libstd/panic.rs b/src/libstd/panic.rs index 3677bd27b1619..83df54f183014 100644 --- a/src/libstd/panic.rs +++ b/src/libstd/panic.rs @@ -84,7 +84,7 @@ pub use panicking::{take_handler, set_handler, PanicInfo, Location}; /// recover safe. The general idea is that any mutable state which can be shared /// across `recover` is not recover safe by default. This is because it is very /// easy to witness a broken invariant outside of `recover` as the data is -/// simply accesed as usual. +/// simply accessed as usual. /// /// Types like `&Mutex`, however, are recover safe because they implement /// poisoning by default. They still allow witnessing a broken invariant, but diff --git a/src/test/compile-fail/issue-30438-c.rs b/src/test/compile-fail/issue-30438-c.rs index 06d391af559cc..2b4d0dc339bf0 100644 --- a/src/test/compile-fail/issue-30438-c.rs +++ b/src/test/compile-fail/issue-30438-c.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -// Simplfied regression test for #30438, inspired by arielb1. +// Simplified regression test for #30438, inspired by arielb1. trait Trait { type Out; } diff --git a/src/test/compile-fail/traits-inductive-overflow-supertrait-oibit.rs b/src/test/compile-fail/traits-inductive-overflow-supertrait-oibit.rs index 1362f8ac0aef5..ec8db996600d1 100644 --- a/src/test/compile-fail/traits-inductive-overflow-supertrait-oibit.rs +++ b/src/test/compile-fail/traits-inductive-overflow-supertrait-oibit.rs @@ -9,7 +9,7 @@ // except according to those terms. // OIBIT-based version of #29859, supertrait version. Test that using -// a simple OIBIT `..` impl alone still doesn't allow arbitary bounds +// a simple OIBIT `..` impl alone still doesn't allow arbitrary bounds // to be synthesized. #![feature(optin_builtin_traits)] diff --git a/src/test/run-pass/mir_trans_calls.rs b/src/test/run-pass/mir_trans_calls.rs index 8fdedb6581fab..fc45fbf727840 100644 --- a/src/test/run-pass/mir_trans_calls.rs +++ b/src/test/run-pass/mir_trans_calls.rs @@ -113,7 +113,7 @@ fn test_fn_object(f: &Fn(i32, i32) -> i32, x: i32, y: i32) -> i32 { fn test_fn_impl(f: &&Fn(i32, i32) -> i32, x: i32, y: i32) -> i32 { // This call goes through the Fn implementation for &Fn provided in // core::ops::impls. It expands to a static Fn::call() that calls the - // Fn::call() implemenation of the object shim underneath. + // Fn::call() implementation of the object shim underneath. f(x, y) } From 47e81ed3ab2f10e6bcad45fe1b93b6d8fde10aa0 Mon Sep 17 00:00:00 2001 From: Steve Klabnik Date: Tue, 9 Feb 2016 12:02:55 -0500 Subject: [PATCH 4/6] Improve docs for Drain on String This is the last bit of String docs needed to Close #29376 --- src/libcollections/string.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/libcollections/string.rs b/src/libcollections/string.rs index 7f6def6832047..2366432e6a2c0 100644 --- a/src/libcollections/string.rs +++ b/src/libcollections/string.rs @@ -1842,6 +1842,12 @@ impl fmt::Write for String { } /// A draining iterator for `String`. +/// +/// This struct is created by the [`drain()`] method on [`String`]. See its +/// documentation for more. +/// +/// [`drain()`]: struct.String.html#method.drain +/// [`String`]: struct.String.html #[stable(feature = "drain", since = "1.6.0")] pub struct Drain<'a> { /// Will be used as &'a mut String in the destructor From 3d421add22b9d738c6dab5db8a44626e0b347bfb Mon Sep 17 00:00:00 2001 From: Steve Klabnik Date: Tue, 9 Feb 2016 12:54:53 -0500 Subject: [PATCH 5/6] Properly document tuples Fixes #29339 --- src/libcore/tuple.rs | 19 +------- src/libstd/primitive_docs.rs | 92 +++++++++++++++++++++++++----------- 2 files changed, 66 insertions(+), 45 deletions(-) diff --git a/src/libcore/tuple.rs b/src/libcore/tuple.rs index 4127e182e1d0f..abaabfd129b38 100644 --- a/src/libcore/tuple.rs +++ b/src/libcore/tuple.rs @@ -8,24 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -//! A finite heterogeneous sequence, `(T, U, ..)` -//! -//! To access a single element of a tuple one can use the `.0` -//! field access syntax. -//! -//! Indexing starts from zero, so `.0` returns first value, `.1` -//! returns second value, and so on. In general, a tuple with *N* -//! elements has field accessors from 0 to *N* - 1. -//! -//! If every type inside a tuple implements one of the following -//! traits, then a tuple itself also implements it. -//! -//! * `Clone` -//! * `PartialEq` -//! * `Eq` -//! * `PartialOrd` -//! * `Ord` -//! * `Default` +// See src/libstd/primitive_docs.rs for documentation. use clone::Clone; use cmp::*; diff --git a/src/libstd/primitive_docs.rs b/src/libstd/primitive_docs.rs index ed59c51b0f0d8..7d6140326f1bf 100644 --- a/src/libstd/primitive_docs.rs +++ b/src/libstd/primitive_docs.rs @@ -357,50 +357,88 @@ mod prim_str { } // /// A finite heterogeneous sequence, `(T, U, ..)`. /// -/// To access the _N_-th element of a tuple one can use `N` itself -/// as a field of the tuple. +/// Let's cover each of those in turn: /// -/// Indexing starts from zero, so `0` returns first value, `1` -/// returns second value, and so on. In general, a tuple with _S_ -/// elements provides aforementioned fields from `0` to `S-1`. +/// Tuples are *finite*. In other words, a tuple has a length. Here's a tuple +/// of length `3`: +/// +/// ``` +/// ("hello", 5, 'c'); +/// ``` +/// +/// Tuples are *heterogeneous*. This means that each element of the tuple can +/// have a different type. In that tuple above, it has the type: +/// +/// ```rust,ignore +/// (&'static str, i32, char) +/// ``` +/// +/// Tuples are a *sequence*. This means that they can be accessed by position; +/// this is called 'tuple indexing', and it looks like this: +/// +/// ```rust +/// let tuple = ("hello", 5, 'c'); +/// +/// assert_eq!(tuple.0, "hello"); +/// assert_eq!(tuple.1, 5); +/// assert_eq!(tuple.2, 'c'); +/// ``` +/// +/// For more about tuples, see [the book](../../book/primitive-types.html#tuples). +/// +/// # Trait implementations /// /// If every type inside a tuple implements one of the following /// traits, then a tuple itself also implements it. /// -/// * `Clone` -/// * `PartialEq` -/// * `Eq` -/// * `PartialOrd` -/// * `Ord` -/// * `Debug` -/// * `Default` -/// * `Hash` +/// * [`Clone`] +/// * [`PartialEq`] +/// * [`Eq`] +/// * [`PartialOrd`] +/// * [`Ord`] +/// * [`Debug`] +/// * [`Default`] +/// * [`Hash`] +/// +/// [`Clone`]: ../clone/trait.Clone.html +/// [`PartialEq`]: ../cmp/trait.PartialEq.html +/// [`Eq`]: ../cmp/trait.Eq.html +/// [`PartialOrd`]: ../cmp/trait.PartialOrd.html +/// [`Ord`]: ../cmp/trait.Ord.html +/// [`Debug`]: ../fmt/trait.Debug.html +/// [`Default`]: ../default/trait.Default.html +/// [`Hash`]: ../hash/trait.Hash.html /// /// # Examples /// -/// Accessing elements of a tuple at specified indices: +/// Basic usage: /// /// ``` -/// let x = ("colorless", "green", "ideas", "sleep", "furiously"); -/// assert_eq!(x.3, "sleep"); +/// let tuple = ("hello", 5, 'c'); /// -/// let v = (3, 3); -/// let u = (1, -5); -/// assert_eq!(v.0 * u.0 + v.1 * u.1, -12); +/// assert_eq!(tuple.0, "hello"); /// ``` /// -/// Using traits implemented for tuples: +/// Tuples are often used as a return type when you want to return more than +/// one value: /// /// ``` -/// let a = (1, 2); -/// let b = (3, 4); -/// assert!(a != b); +/// fn calculate_point() -> (i32, i32) { +/// // Don't do a calculation, that's not the point of the example +/// (4, 5) +/// } +/// +/// let point = calculate_point(); +/// +/// assert_eq!(point.0, 4); +/// assert_eq!(point.1, 5); +/// +/// // Combining this with patterns can be nicer. /// -/// let c = b.clone(); -/// assert!(b == c); +/// let (x, y) = calcualte_point(); /// -/// let d : (u32, f32) = Default::default(); -/// assert_eq!(d, (0, 0.0f32)); +/// assert_eq!(x, 4); +/// assert_eq!(y, 5); /// ``` /// mod prim_tuple { } From 55ff2b931c6040d5d1e5f2b9bd1afb08428ede8c Mon Sep 17 00:00:00 2001 From: Steve Klabnik Date: Tue, 9 Feb 2016 13:33:02 -0500 Subject: [PATCH 6/6] make note of arity and 32-length restriction --- src/libstd/primitive_docs.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/libstd/primitive_docs.rs b/src/libstd/primitive_docs.rs index 7d6140326f1bf..06bb2ad449bb8 100644 --- a/src/libstd/primitive_docs.rs +++ b/src/libstd/primitive_docs.rs @@ -366,6 +366,9 @@ mod prim_str { } /// ("hello", 5, 'c'); /// ``` /// +/// 'Length' is also sometimes called 'arity' here; each tuple of a different +/// length is a different, distinct type. +/// /// Tuples are *heterogeneous*. This means that each element of the tuple can /// have a different type. In that tuple above, it has the type: /// @@ -409,6 +412,9 @@ mod prim_str { } /// [`Default`]: ../default/trait.Default.html /// [`Hash`]: ../hash/trait.Hash.html /// +/// Due to a temporary restriction in Rust's type system, these traits are only +/// implemented on tuples of arity 32 or less. In the future, this may change. +/// /// # Examples /// /// Basic usage: