Skip to content
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

Collection of fixes for the Strings chapter. #1212

Merged
merged 6 commits into from
Jul 2, 2019
Merged
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
22 changes: 11 additions & 11 deletions src/std/str.md
Original file line number Diff line number Diff line change
Expand Up @@ -112,42 +112,42 @@ fn main() {
}
```

Want a string that's not UTF-8? (Remember, `str` and `String` must be valid UTF-8)
Want a string that's not UTF-8? (Remember, `str` and `String` must be valid UTF-8).
Or maybe you want an array of bytes that's mostly text? Byte strings to the rescue!

```rust, editable
use std::str;

fn main() {
// Note that this is not actually a &str
let bytestring: &[u8; 20] = b"this is a bytestring";
// Note that this is not actually a `&str`
let bytestring: &[u8; 21] = b"this is a byte string";

// Byte arrays don't have Display so printing them is a bit limited
println!("A bytestring: {:?}", bytestring);
// Byte arrays don't have the `Display` trait, so printing them is a bit limited
println!("A byte string: {:?}", bytestring);

// Bytestrings can have byte escapes...
// Byte strings can have byte escapes...
let escaped = b"\x52\x75\x73\x74 as bytes";
// ...but no unicode escapes
// let escaped = b"\u{211D} is not allowed";
println!("Some escaped bytes: {:?}", escaped);


// Raw bytestrings work just like raw strings
// Raw byte strings work just like raw strings
let raw_bytestring = br"\u{211D} is not escaped here";
println!("{:?}", raw_bytestring);

// Converting a byte array to str can fail
// Converting a byte array to `str` can fail
if let Ok(my_str) = str::from_utf8(raw_bytestring) {
println!("And the same as text: '{}'", my_str);
}

let quotes = br#"You can also use "fancier" formatting, \
let _quotes = br#"You can also use "fancier" formatting, \
like with normal raw strings"#;

// Bytestrings don't have to be UTF-8
// Byte strings don't have to be UTF-8
let shift_jis = b"\x82\xe6\x82\xa8\x82\xb1\x82"; // "ようこそ" in SHIFT-JIS

// But then they can't always be converted to str
// But then they can't always be converted to `str`
match str::from_utf8(shift_jis) {
Ok(my_str) => println!("Conversion successful: '{}'", my_str),
Err(e) => println!("Conversion failed: {:?}", e),
Expand Down