Logo

Programming-Idioms

History of Idiom 46 > diff from v48 to v49

Edit summary for version 49 by programming-idioms.org:
[Rust] +DemoURL

Version 48

2020-07-15, 15:45:13

Version 49

2020-07-18, 20:56:41

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