From b6cc0995b0bae79a5c4c3823fb462dd697d9a2e9 Mon Sep 17 00:00:00 2001 From: Steve Klabnik Date: Thu, 7 Jan 2016 14:54:17 -0500 Subject: [PATCH] Add some examples to std::string Fixes #30345 --- src/libcollections/string.rs | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/src/libcollections/string.rs b/src/libcollections/string.rs index d2cbcad875f..d9cafd53a85 100644 --- a/src/libcollections/string.rs +++ b/src/libcollections/string.rs @@ -16,6 +16,42 @@ //! //! [`String`]: struct.String.html //! [`ToString`]: trait.ToString.html +//! +//! # Examples +//! +//! There are multiple ways to create a new `String` from a string literal: +//! +//! ```rust +//! let s = "Hello".to_string(); +//! +//! let s = String::from("world"); +//! let s: String = "also this".into(); +//! ``` +//! +//! You can create a new `String` from an existing one by concatenating with +//! `+`: +//! +//! ```rust +//! let s = "Hello".to_string(); +//! +//! let message = s + " world!"; +//! ``` +//! +//! If you have a vector of valid UTF-8 bytes, you can make a `String` out of +//! it. You can do the reverse too. +//! +//! ```rust +//! let sparkle_heart = vec![240, 159, 146, 150]; +//! +//! // We know these bytes are valid, so we'll use `unwrap()`. +//! let sparkle_heart = String::from_utf8(sparkle_heart).unwrap(); +//! +//! assert_eq!("💖", sparkle_heart); +//! +//! let bytes = sparkle_heart.into_bytes(); +//! +//! assert_eq!(bytes, [240, 159, 146, 150]); +//! ``` #![stable(feature = "rust1", since = "1.0.0")]