diff options
| author | Huon Wilson <dbau.pp+github@gmail.com> | 2014-06-01 14:11:01 +1000 |
|---|---|---|
| committer | Huon Wilson <dbau.pp+github@gmail.com> | 2014-06-01 14:13:10 +1000 |
| commit | aec7f469020c0fc1846a66fc607694644525a459 (patch) | |
| tree | ce4b7ef8a490b726949c01ed8cd908a755115461 | |
| parent | 2652ba1505051160b946830c69c960ed283851d8 (diff) | |
| download | rust-aec7f469020c0fc1846a66fc607694644525a459.tar.gz rust-aec7f469020c0fc1846a66fc607694644525a459.zip | |
doc: add an `.as_slice` example to the cheatsheet.
A lot of questions about this on IRC and stackoverflow.
| -rw-r--r-- | src/doc/complement-cheatsheet.md | 18 |
1 files changed, 18 insertions, 0 deletions
diff --git a/src/doc/complement-cheatsheet.md b/src/doc/complement-cheatsheet.md index 1c3352a829c..dd05fca5531 100644 --- a/src/doc/complement-cheatsheet.md +++ b/src/doc/complement-cheatsheet.md @@ -80,6 +80,24 @@ let x = bytes!(72u8,"ello ",0xF0,0x90,0x80,"World!"); let y = str::from_utf8_lossy(x); ~~~ +**`Vec<T>`/`String` to `&[T]`/`&str`** + +The `.as_slice` method on each type provides a borrowed slice pointing +to the contents of a `Vec` or `String`. The slice points directly to +the data already stored in the vector or string, and so is a very +cheap operation (no allocations or complicated computations required). + +~~~ +let vec: Vec<u32> = vec![1, 2, 3]; +let slice: &[u32] = vec.as_slice(); + +let string: String = "foo bar".to_string(); +let str_slice: &str = string.as_slice(); +~~~ + +`Vec` also provides the `.as_mut_slice` method for viewing the +contained data as a `&mut [T]`. + # File operations ## How do I read from a file? |
