Skip to content

Commit b6cc099

Browse files
committed
Add some examples to std::string
Fixes #30345
1 parent 03f4950 commit b6cc099

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

src/libcollections/string.rs

+36
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,42 @@
1616
//!
1717
//! [`String`]: struct.String.html
1818
//! [`ToString`]: trait.ToString.html
19+
//!
20+
//! # Examples
21+
//!
22+
//! There are multiple ways to create a new `String` from a string literal:
23+
//!
24+
//! ```rust
25+
//! let s = "Hello".to_string();
26+
//!
27+
//! let s = String::from("world");
28+
//! let s: String = "also this".into();
29+
//! ```
30+
//!
31+
//! You can create a new `String` from an existing one by concatenating with
32+
//! `+`:
33+
//!
34+
//! ```rust
35+
//! let s = "Hello".to_string();
36+
//!
37+
//! let message = s + " world!";
38+
//! ```
39+
//!
40+
//! If you have a vector of valid UTF-8 bytes, you can make a `String` out of
41+
//! it. You can do the reverse too.
42+
//!
43+
//! ```rust
44+
//! let sparkle_heart = vec![240, 159, 146, 150];
45+
//!
46+
//! // We know these bytes are valid, so we'll use `unwrap()`.
47+
//! let sparkle_heart = String::from_utf8(sparkle_heart).unwrap();
48+
//!
49+
//! assert_eq!("💖", sparkle_heart);
50+
//!
51+
//! let bytes = sparkle_heart.into_bytes();
52+
//!
53+
//! assert_eq!(bytes, [240, 159, 146, 150]);
54+
//! ```
1955
2056
#![stable(feature = "rust1", since = "1.0.0")]
2157

0 commit comments

Comments
 (0)