提交 72ee4721 编写于 作者: S Steve Klabnik

Rollup merge of #24848 - bluss:deref-string, r=alexcrichton

Improve example for as_string and add example for as_vec

Provide a better example of `as_string` / `DerefString`'s unique capabilities.
Use an example where (for an unspecified reason) you need a &String, and
show how `as_string` solves the problem without needing an allocation.
......@@ -951,12 +951,13 @@ fn deref<'b>(&'b self) -> &'b String {
/// # #![feature(collections)]
/// use std::string::as_string;
///
/// fn string_consumer(s: String) {
/// assert_eq!(s, "foo".to_string());
/// // Let's pretend we have a function that requires `&String`
/// fn string_consumer(s: &String) {
/// assert_eq!(s, "foo");
/// }
///
/// let string = as_string("foo").clone();
/// string_consumer(string);
/// // Provide a `&String` from a `&str` without allocating
/// string_consumer(&as_string("foo"));
/// ```
#[unstable(feature = "collections")]
pub fn as_string<'a>(x: &'a str) -> DerefString<'a> {
......
......@@ -1915,6 +1915,22 @@ fn drop(&mut self) {
}
/// Converts a slice to a wrapper type providing a `&Vec<T>` reference.
///
/// # Examples
///
/// ```
/// # #![feature(collections)]
/// use std::vec::as_vec;
///
/// // Let's pretend we have a function that requires `&Vec<i32>`
/// fn vec_consumer(s: &Vec<i32>) {
/// assert_eq!(s, &[1, 2, 3]);
/// }
///
/// // Provide a `&Vec<i32>` from a `&[i32]` without allocating
/// let values = [1, 2, 3];
/// vec_consumer(&as_vec(&values));
/// ```
#[unstable(feature = "collections")]
pub fn as_vec<'a, T>(x: &'a [T]) -> DerefVec<'a, T> {
unsafe {
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册