205. strip_prefix / strip_suffix — Remove a Prefix Once, Not Every Repeat
Reaching for trim_start_matches to peel off a "--" or a leading slash? It strips every repeated match and silently does nothing when there’s no match. strip_prefix removes exactly one and tells you whether it hit.
The Problem
trim_start_matches keeps eating as long as the pattern matches, which is rarely what “remove the prefix” means:
| |
It also can’t tell you whether anything was removed — a non-match returns the string unchanged, so you can’t branch on it.
The Fix: strip_prefix
strip_prefix removes one occurrence and returns an Option: Some(rest) on a hit, None when the prefix isn’t there.
| |
The Option is the real win: it doubles as a “did this start with the prefix?” test. Parsing a CLI flag becomes a one-liner:
| |
Its Mirror: strip_suffix
Same deal at the other end — perfect for trimming a known extension or unit without slicing indices by hand:
| |
Use trim_start_matches / trim_end_matches only when you genuinely want to collapse a run of repeats. For peeling one known prefix or suffix — and knowing if it was there — strip_prefix and strip_suffix say exactly what you mean.