Logo

Programming-Idioms

History of Idiom 46 > diff from v52 to v53

Edit summary for version 53 by programming-idioms.org:
[Rust] Cleanup demo

Version 52

2020-07-18, 21:01:56

Version 53

2020-07-18, 21:14:28

Idiom #46 Extract beginning of string (prefix)

Create string t consisting of the 5 first characters of string s.

Illustration

Idiom #46 Extract beginning of string (prefix)

Create string t consisting of the 5 first characters of string s.

Illustration
Variables
t,s
Variables
t,s
Code
let t = s.char_indices().nth(5).map_or(s, |(i, _)| &s[..i]);
Code
let t = s.char_indices().nth(5).map_or(s, |(i, _)| &s[..i]);
Comments bubble
Rust strings are encoded in UTF-8, and can be multiple bytes wide, which text processing code must account for. Naively slicing the string could cause it to panic if, for example, the string contained 😁

It should be noted that these logical "characters" don't have much semantic meaning either: Unicode characters are combined into "graphemes" before being displayed to the user, which would need to be identified using the unicode-segmentation crate
Comments bubble
Rust strings are encoded in UTF-8, and can be multiple bytes wide, which text processing code must account for. Naively slicing the string could cause it to panic if, for example, the string contained 😁

It should be noted that these logical "characters" don't have much semantic meaning either: Unicode characters are combined into "graphemes" before being displayed to the user, which would need to be identified using the unicode-segmentation crate
Doc URL
https://doc.rust-lang.org/std/primitive.str.html#method.char_indices
Doc URL
https://doc.rust-lang.org/std/primitive.str.html#method.char_indices
Demo URL
https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=7c9a3cd62de8eef2d7533be1c6853c6f
Demo URL
https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=c4381ace83459b3f800d9ec0f4b8925f