Skip to content

doc: add an .as_slice example to the cheatsheet. #14578

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions src/doc/complement-cheatsheet.md
Original file line number Diff line number Diff line change
Expand Up @@ -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?
Expand Down