]> git.lizzy.rs Git - rust.git/blob - src/docs/manual_strip.txt
Auto merge of #9421 - xphoniex:fix-#9420, r=giraffate
[rust.git] / src / docs / manual_strip.txt
1 ### What it does
2 Suggests using `strip_{prefix,suffix}` over `str::{starts,ends}_with` and slicing using
3 the pattern's length.
4
5 ### Why is this bad?
6 Using `str:strip_{prefix,suffix}` is safer and may have better performance as there is no
7 slicing which may panic and the compiler does not need to insert this panic code. It is
8 also sometimes more readable as it removes the need for duplicating or storing the pattern
9 used by `str::{starts,ends}_with` and in the slicing.
10
11 ### Example
12 ```
13 let s = "hello, world!";
14 if s.starts_with("hello, ") {
15     assert_eq!(s["hello, ".len()..].to_uppercase(), "WORLD!");
16 }
17 ```
18 Use instead:
19 ```
20 let s = "hello, world!";
21 if let Some(end) = s.strip_prefix("hello, ") {
22     assert_eq!(end.to_uppercase(), "WORLD!");
23 }
24 ```