Skip to content

Commit dfaea70

Browse files
committed
auto merge of #14578 : huonw/rust/as_slice-cheatsheet, r=sfackler
doc: add an `.as_slice` example to the cheatsheet. A lot of questions about this on IRC and stackoverflow.
2 parents 064dbb9 + aec7f46 commit dfaea70

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

src/doc/complement-cheatsheet.md

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,24 @@ let x = bytes!(72u8,"ello ",0xF0,0x90,0x80,"World!");
8080
let y = str::from_utf8_lossy(x);
8181
~~~
8282

83+
**`Vec<T>`/`String` to `&[T]`/`&str`**
84+
85+
The `.as_slice` method on each type provides a borrowed slice pointing
86+
to the contents of a `Vec` or `String`. The slice points directly to
87+
the data already stored in the vector or string, and so is a very
88+
cheap operation (no allocations or complicated computations required).
89+
90+
~~~
91+
let vec: Vec<u32> = vec![1, 2, 3];
92+
let slice: &[u32] = vec.as_slice();
93+
94+
let string: String = "foo bar".to_string();
95+
let str_slice: &str = string.as_slice();
96+
~~~
97+
98+
`Vec` also provides the `.as_mut_slice` method for viewing the
99+
contained data as a `&mut [T]`.
100+
83101
# File operations
84102

85103
## How do I read from a file?

0 commit comments

Comments
 (0)