Logo

Programming-Idioms

History of Idiom 46 > diff from v47 to v48

Edit summary for version 48 by Plecra:
New Rust implementation by user [Plecra]

Version 47

2020-05-10, 21:35:56

Version 48

2020-07-15, 15:45:13

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]);
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