Skip to content

Commit 72ee472

Browse files
committed
Rollup merge of rust-lang#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.
2 parents 130240a + 84ef3b5 commit 72ee472

File tree

2 files changed

+21
-4
lines changed

2 files changed

+21
-4
lines changed

src/libcollections/string.rs

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -951,12 +951,13 @@ impl<'a> Deref for DerefString<'a> {
951951
/// # #![feature(collections)]
952952
/// use std::string::as_string;
953953
///
954-
/// fn string_consumer(s: String) {
955-
/// assert_eq!(s, "foo".to_string());
954+
/// // Let's pretend we have a function that requires `&String`
955+
/// fn string_consumer(s: &String) {
956+
/// assert_eq!(s, "foo");
956957
/// }
957958
///
958-
/// let string = as_string("foo").clone();
959-
/// string_consumer(string);
959+
/// // Provide a `&String` from a `&str` without allocating
960+
/// string_consumer(&as_string("foo"));
960961
/// ```
961962
#[unstable(feature = "collections")]
962963
pub fn as_string<'a>(x: &'a str) -> DerefString<'a> {

src/libcollections/vec.rs

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1915,6 +1915,22 @@ impl<'a, T> Drop for DerefVec<'a, T> {
19151915
}
19161916

19171917
/// Converts a slice to a wrapper type providing a `&Vec<T>` reference.
1918+
///
1919+
/// # Examples
1920+
///
1921+
/// ```
1922+
/// # #![feature(collections)]
1923+
/// use std::vec::as_vec;
1924+
///
1925+
/// // Let's pretend we have a function that requires `&Vec<i32>`
1926+
/// fn vec_consumer(s: &Vec<i32>) {
1927+
/// assert_eq!(s, &[1, 2, 3]);
1928+
/// }
1929+
///
1930+
/// // Provide a `&Vec<i32>` from a `&[i32]` without allocating
1931+
/// let values = [1, 2, 3];
1932+
/// vec_consumer(&as_vec(&values));
1933+
/// ```
19181934
#[unstable(feature = "collections")]
19191935
pub fn as_vec<'a, T>(x: &'a [T]) -> DerefVec<'a, T> {
19201936
unsafe {

0 commit comments

Comments
 (0)