44. split_once — Split a String Exactly Once
When you need to split a string on the first occurrence of a delimiter, split_once is cleaner than anything you’d write by hand. Stable since Rust 1.52.
Parsing key=value pairs, HTTP headers, file paths — almost everywhere you split a string, you only care about the first separator. Before split_once, you’d reach for .find() plus index arithmetic:
The old way
| |
Works, but it’s four lines of noise. The index arithmetic is easy to get wrong, and .trim() is a separate step.
With split_once
| |
One line. The delimiter is consumed, both sides are returned, and you pattern-match directly into named bindings.
Handling missing delimiters
split_once returns Option<(&str, &str)> — None if the delimiter isn’t found. This makes it composable with ? or if let:
| |
Note the last case: split_once stops at the first =. The rest of the string — a=b=c — is kept intact in the second half. That’s usually exactly what you want.
rsplit_once — split from the right
When you need the last delimiter instead of the first, rsplit_once has you covered:
| |
Multi-char delimiters work too
The delimiter can be any pattern — a char, a &str, or even a closure:
| |
Whenever you reach for .splitn(2, ...) just to grab two halves, replace it with split_once — the intent is clearer and the return type is more ergonomic.