Handle fallout in documentation

Tweak the tutorial's section on vectors and strings, to slightly clarify
the difference between fixed-size vectors, vectors, and slices.
This commit is contained in:
Kevin Ballard 2014-05-04 20:54:02 -07:00
parent 752048a271
commit eab6bb2ece
8 changed files with 81 additions and 79 deletions

View File

@ -266,8 +266,8 @@ Iterators offer generic conversion to containers with the `collect` adaptor:
~~~
let xs = [0, 1, 1, 2, 3, 5, 8];
let ys = xs.iter().rev().skip(1).map(|&x| x * 2).collect::<~[int]>();
assert_eq!(ys, ~[10, 6, 4, 2, 2, 0]);
let ys = xs.iter().rev().skip(1).map(|&x| x * 2).collect::<Vec<int>>();
assert_eq!(ys, vec![10, 6, 4, 2, 2, 0]);
~~~
The method requires a type hint for the container type, if the surrounding code
@ -278,14 +278,14 @@ implementing the `FromIterator` trait. For example, the implementation for
vectors is as follows:
~~~ {.ignore}
impl<A> FromIterator<A> for ~[A] {
pub fn from_iter<T: Iterator<A>>(iterator: &mut T) -> ~[A] {
impl<T> FromIterator<T> for Vec<T> {
fn from_iter<I:Iterator<A>>(mut iterator: I) -> Vec<T> {
let (lower, _) = iterator.size_hint();
let mut xs = with_capacity(lower);
for x in iterator {
xs.push(x);
let mut vector = Vec::with_capacity(lower);
for element in iterator {
vector.push(element);
}
xs
vector
}
}
~~~

View File

@ -3598,18 +3598,18 @@ and the cast expression in `main`.
Within the body of an item that has type parameter declarations, the names of its type parameters are types:
~~~~
fn map<A: Clone, B: Clone>(f: |A| -> B, xs: &[A]) -> ~[B] {
fn map<A: Clone, B: Clone>(f: |A| -> B, xs: &[A]) -> Vec<B> {
if xs.len() == 0 {
return ~[];
return vec![];
}
let first: B = f(xs[0].clone());
let rest: ~[B] = map(f, xs.slice(1, xs.len()));
return ~[first] + rest;
let rest: Vec<B> = map(f, xs.slice(1, xs.len()));
return [first] + rest;
}
~~~~
Here, `first` has type `B`, referring to `map`'s `B` type parameter;
and `rest` has type `~[B]`, a vector type with element type `B`.
and `rest` has type `Vec<B>`, a vector type with element type `B`.
### Self types

View File

@ -1588,8 +1588,8 @@ let mut numbers = vec![1, 2, 3];
numbers.push(4);
numbers.push(5);
// The type of a unique vector is written as `~[int]`
let more_numbers: ~[int] = numbers.move_iter().collect();
// The type of a unique vector is written as `Vec<int>`
let more_numbers: Vec<int> = numbers.move_iter().map(|i| i+1).collect();
// The original `numbers` value can no longer be used, due to move semantics.
@ -1633,7 +1633,7 @@ view[0] = 5;
let ys: &mut [int] = &mut [1, 2, 3];
~~~
Square brackets denote indexing into a vector:
Square brackets denote indexing into a slice or fixed-size vector:
~~~~
# enum Crayon { Almond, AntiqueBrass, Apricot,
@ -1647,7 +1647,7 @@ match crayons[0] {
}
~~~~
A vector can be destructured using pattern matching:
A slice or fixed-size vector can be destructured using pattern matching:
~~~~
let numbers: &[int] = &[1, 2, 3];
@ -1660,9 +1660,10 @@ let score = match numbers {
~~~~
Both vectors and strings support a number of useful [methods](#methods),
defined in [`std::vec`] and [`std::str`].
defined in [`std::vec`], [`std::slice`], and [`std::str`].
[`std::vec`]: std/vec/index.html
[`std::slice`]: std/slice/index.html
[`std::str`]: std/str/index.html
# Ownership escape hatches

View File

@ -455,8 +455,8 @@ pub trait Iterator<A> {
///
/// ```rust
/// let a = [1, 2, 3, 4, 5];
/// let b: ~[int] = a.iter().map(|&x| x).collect();
/// assert!(a == b);
/// let b: Vec<int> = a.iter().map(|&x| x).collect();
/// assert!(a.as_slice() == b.as_slice());
/// ```
#[inline]
fn collect<B: FromIterator<A>>(&mut self) -> B {

View File

@ -621,12 +621,12 @@ impl<'a> Iterator<UTF16Item> for UTF16Items<'a> {
/// 0x0073, 0xDD1E, 0x0069, 0x0063,
/// 0xD834];
///
/// assert_eq!(str::utf16_items(v).collect::<~[_]>(),
/// ~[ScalarValue('𝄞'),
/// ScalarValue('m'), ScalarValue('u'), ScalarValue('s'),
/// LoneSurrogate(0xDD1E),
/// ScalarValue('i'), ScalarValue('c'),
/// LoneSurrogate(0xD834)]);
/// assert_eq!(str::utf16_items(v).collect::<Vec<_>>(),
/// vec![ScalarValue('𝄞'),
/// ScalarValue('m'), ScalarValue('u'), ScalarValue('s'),
/// LoneSurrogate(0xDD1E),
/// ScalarValue('i'), ScalarValue('c'),
/// LoneSurrogate(0xD834)]);
/// ```
pub fn utf16_items<'a>(v: &'a [u16]) -> UTF16Items<'a> {
UTF16Items { iter : v.iter() }
@ -896,8 +896,8 @@ pub trait StrSlice<'a> {
/// # Example
///
/// ```rust
/// let v: ~[char] = "abc åäö".chars().collect();
/// assert_eq!(v, ~['a', 'b', 'c', ' ', 'å', 'ä', 'ö']);
/// let v: Vec<char> = "abc åäö".chars().collect();
/// assert_eq!(v, vec!['a', 'b', 'c', ' ', 'å', 'ä', 'ö']);
/// ```
fn chars(&self) -> Chars<'a>;
@ -925,14 +925,14 @@ pub trait StrSlice<'a> {
/// # Example
///
/// ```rust
/// let v: ~[&str] = "Mary had a little lamb".split(' ').collect();
/// assert_eq!(v, ~["Mary", "had", "a", "little", "lamb"]);
/// let v: Vec<&str> = "Mary had a little lamb".split(' ').collect();
/// assert_eq!(v, vec!["Mary", "had", "a", "little", "lamb"]);
///
/// let v: ~[&str] = "abc1def2ghi".split(|c: char| c.is_digit()).collect();
/// assert_eq!(v, ~["abc", "def", "ghi"]);
/// let v: Vec<&str> = "abc1def2ghi".split(|c: char| c.is_digit()).collect();
/// assert_eq!(v, vec!["abc", "def", "ghi"]);
///
/// let v: ~[&str] = "lionXXtigerXleopard".split('X').collect();
/// assert_eq!(v, ~["lion", "", "tiger", "leopard"]);
/// let v: Vec<&str> = "lionXXtigerXleopard".split('X').collect();
/// assert_eq!(v, vec!["lion", "", "tiger", "leopard"]);
/// ```
fn split<Sep: CharEq>(&self, sep: Sep) -> CharSplits<'a, Sep>;
@ -943,14 +943,14 @@ pub trait StrSlice<'a> {
/// # Example
///
/// ```rust
/// let v: ~[&str] = "Mary had a little lambda".splitn(' ', 2).collect();
/// assert_eq!(v, ~["Mary", "had", "a little lambda"]);
/// let v: Vec<&str> = "Mary had a little lambda".splitn(' ', 2).collect();
/// assert_eq!(v, vec!["Mary", "had", "a little lambda"]);
///
/// let v: ~[&str] = "abc1def2ghi".splitn(|c: char| c.is_digit(), 1).collect();
/// assert_eq!(v, ~["abc", "def2ghi"]);
/// let v: Vec<&str> = "abc1def2ghi".splitn(|c: char| c.is_digit(), 1).collect();
/// assert_eq!(v, vec!["abc", "def2ghi"]);
///
/// let v: ~[&str] = "lionXXtigerXleopard".splitn('X', 2).collect();
/// assert_eq!(v, ~["lion", "", "tigerXleopard"]);
/// let v: Vec<&str> = "lionXXtigerXleopard".splitn('X', 2).collect();
/// assert_eq!(v, vec!["lion", "", "tigerXleopard"]);
/// ```
fn splitn<Sep: CharEq>(&self, sep: Sep, count: uint) -> CharSplitsN<'a, Sep>;
@ -963,20 +963,20 @@ pub trait StrSlice<'a> {
/// # Example
///
/// ```rust
/// let v: ~[&str] = "A.B.".split_terminator('.').collect();
/// assert_eq!(v, ~["A", "B"]);
/// let v: Vec<&str> = "A.B.".split_terminator('.').collect();
/// assert_eq!(v, vec!["A", "B"]);
///
/// let v: ~[&str] = "A..B..".split_terminator('.').collect();
/// assert_eq!(v, ~["A", "", "B", ""]);
/// let v: Vec<&str> = "A..B..".split_terminator('.').collect();
/// assert_eq!(v, vec!["A", "", "B", ""]);
///
/// let v: ~[&str] = "Mary had a little lamb".split(' ').rev().collect();
/// assert_eq!(v, ~["lamb", "little", "a", "had", "Mary"]);
/// let v: Vec<&str> = "Mary had a little lamb".split(' ').rev().collect();
/// assert_eq!(v, vec!["lamb", "little", "a", "had", "Mary"]);
///
/// let v: ~[&str] = "abc1def2ghi".split(|c: char| c.is_digit()).rev().collect();
/// assert_eq!(v, ~["ghi", "def", "abc"]);
/// let v: Vec<&str> = "abc1def2ghi".split(|c: char| c.is_digit()).rev().collect();
/// assert_eq!(v, vec!["ghi", "def", "abc"]);
///
/// let v: ~[&str] = "lionXXtigerXleopard".split('X').rev().collect();
/// assert_eq!(v, ~["leopard", "tiger", "", "lion"]);
/// let v: Vec<&str> = "lionXXtigerXleopard".split('X').rev().collect();
/// assert_eq!(v, vec!["leopard", "tiger", "", "lion"]);
/// ```
fn split_terminator<Sep: CharEq>(&self, sep: Sep) -> CharSplits<'a, Sep>;
@ -991,14 +991,14 @@ pub trait StrSlice<'a> {
/// # Example
///
/// ```rust
/// let v: ~[&str] = "Mary had a little lamb".rsplitn(' ', 2).collect();
/// assert_eq!(v, ~["lamb", "little", "Mary had a"]);
/// let v: Vec<&str> = "Mary had a little lamb".rsplitn(' ', 2).collect();
/// assert_eq!(v, vec!["lamb", "little", "Mary had a"]);
///
/// let v: ~[&str] = "abc1def2ghi".rsplitn(|c: char| c.is_digit(), 1).collect();
/// assert_eq!(v, ~["ghi", "abc1def"]);
/// let v: Vec<&str> = "abc1def2ghi".rsplitn(|c: char| c.is_digit(), 1).collect();
/// assert_eq!(v, vec!["ghi", "abc1def"]);
///
/// let v: ~[&str] = "lionXXtigerXleopard".rsplitn('X', 2).collect();
/// assert_eq!(v, ~["leopard", "tiger", "lionX"]);
/// let v: Vec<&str> = "lionXXtigerXleopard".rsplitn('X', 2).collect();
/// assert_eq!(v, vec!["leopard", "tiger", "lionX"]);
/// ```
fn rsplitn<Sep: CharEq>(&self, sep: Sep, count: uint) -> CharSplitsN<'a, Sep>;
@ -1013,14 +1013,14 @@ pub trait StrSlice<'a> {
/// # Example
///
/// ```rust
/// let v: ~[(uint, uint)] = "abcXXXabcYYYabc".match_indices("abc").collect();
/// assert_eq!(v, ~[(0,3), (6,9), (12,15)]);
/// let v: Vec<(uint, uint)> = "abcXXXabcYYYabc".match_indices("abc").collect();
/// assert_eq!(v, vec![(0,3), (6,9), (12,15)]);
///
/// let v: ~[(uint, uint)] = "1abcabc2".match_indices("abc").collect();
/// assert_eq!(v, ~[(1,4), (4,7)]);
/// let v: Vec<(uint, uint)> = "1abcabc2".match_indices("abc").collect();
/// assert_eq!(v, vec![(1,4), (4,7)]);
///
/// let v: ~[(uint, uint)] = "ababa".match_indices("aba").collect();
/// assert_eq!(v, ~[(0, 3)]); // only the first `aba`
/// let v: Vec<(uint, uint)> = "ababa".match_indices("aba").collect();
/// assert_eq!(v, vec![(0, 3)]); // only the first `aba`
/// ```
fn match_indices(&self, sep: &'a str) -> MatchIndices<'a>;
@ -1029,11 +1029,11 @@ pub trait StrSlice<'a> {
/// # Example
///
/// ```rust
/// let v: ~[&str] = "abcXXXabcYYYabc".split_str("abc").collect();
/// assert_eq!(v, ~["", "XXX", "YYY", ""]);
/// let v: Vec<&str> = "abcXXXabcYYYabc".split_str("abc").collect();
/// assert_eq!(v, vec!["", "XXX", "YYY", ""]);
///
/// let v: ~[&str] = "1abcabc2".split_str("abc").collect();
/// assert_eq!(v, ~["1", "", "2"]);
/// let v: Vec<&str> = "1abcabc2".split_str("abc").collect();
/// assert_eq!(v, vec!["1", "", "2"]);
/// ```
fn split_str(&self, &'a str) -> StrSplits<'a>;
@ -1045,8 +1045,8 @@ pub trait StrSlice<'a> {
///
/// ```rust
/// let four_lines = "foo\nbar\n\nbaz\n";
/// let v: ~[&str] = four_lines.lines().collect();
/// assert_eq!(v, ~["foo", "bar", "", "baz"]);
/// let v: Vec<&str> = four_lines.lines().collect();
/// assert_eq!(v, vec!["foo", "bar", "", "baz"]);
/// ```
fn lines(&self) -> CharSplits<'a, char>;
@ -1058,8 +1058,8 @@ pub trait StrSlice<'a> {
///
/// ```rust
/// let four_lines = "foo\r\nbar\n\r\nbaz\n";
/// let v: ~[&str] = four_lines.lines_any().collect();
/// assert_eq!(v, ~["foo", "bar", "", "baz"]);
/// let v: Vec<&str> = four_lines.lines_any().collect();
/// assert_eq!(v, vec!["foo", "bar", "", "baz"]);
/// ```
fn lines_any(&self) -> AnyLines<'a>;
@ -1071,8 +1071,8 @@ pub trait StrSlice<'a> {
///
/// ```rust
/// let some_words = " Mary had\ta little \n\t lamb";
/// let v: ~[&str] = some_words.words().collect();
/// assert_eq!(v, ~["Mary", "had", "a", "little", "lamb"]);
/// let v: Vec<&str> = some_words.words().collect();
/// assert_eq!(v, vec!["Mary", "had", "a", "little", "lamb"]);
/// ```
fn words(&self) -> Words<'a>;
@ -1469,7 +1469,8 @@ pub trait StrSlice<'a> {
///
/// ```rust
/// let string = "a\nb\nc";
/// let lines: ~[&str] = string.lines().collect();
/// let lines: Vec<&str> = string.lines().collect();
/// let lines = lines.as_slice();
///
/// assert!(string.subslice_offset(lines[0]) == 0); // &"a"
/// assert!(string.subslice_offset(lines[1]) == 2); // &"b"

View File

@ -51,7 +51,7 @@
//! fn main() {
//! let args = os::args();
//!
//! let program = args[0].clone();
//! let program = args.get(0).clone();
//!
//! let opts = [
//! optopt("o", "", "set output file name", "NAME"),

View File

@ -166,14 +166,14 @@ use serialize::{json, Encodable, Decodable};
pub struct TestStruct1 {
data_int: u8,
data_str: ~str,
data_vector: ~[u8],
data_vector: Vec<u8>,
}
// To serialize use the `json::str_encode` to encode an object in a string.
// It calls the generated `Encodable` impl.
fn main() {
let to_encode_object = TestStruct1
{data_int: 1, data_str:"toto".to_owned(), data_vector:~[2,3,4,5]};
{data_int: 1, data_str:"toto".to_owned(), data_vector:vec![2,3,4,5]};
let encoded_str: ~str = json::Encoder::str_encode(&to_encode_object);
// To deserialize use the `json::from_str` and `json::Decoder`
@ -201,7 +201,7 @@ use collections::TreeMap;
pub struct TestStruct1 {
data_int: u8,
data_str: ~str,
data_vector: ~[u8],
data_vector: Vec<u8>,
}
impl ToJson for TestStruct1 {
@ -218,7 +218,7 @@ fn main() {
// Serialization using our impl of to_json
let test2: TestStruct1 = TestStruct1 {data_int: 1, data_str:"toto".to_owned(),
data_vector:~[2,3,4,5]};
data_vector:vec![2,3,4,5]};
let tjson: json::Json = test2.to_json();
let json_str: ~str = tjson.to_str();

View File

@ -76,7 +76,7 @@ Some examples of obvious things you might want to do
let path = Path::new("message.txt");
let mut file = BufferedReader::new(File::open(&path));
let lines: ~[~str] = file.lines().map(|x| x.unwrap()).collect();
let lines: Vec<~str> = file.lines().map(|x| x.unwrap()).collect();
```
* Make a simple TCP client connection and request