Trimming the first character of a `str` in `const`

⚓ Rust    📅 2026-03-23    👤 surdeus    👁️ 2      

surdeus

Any nicer ways to conditionally trim or split the first character of a string in a const function (on stable)? The best I could come up with is this:

if let Some((fst, rst)) = s.split_at_checked(1)
    && fst.as_bytes()[0] == b'#'
{
    s = rst;
}

This works if the string is empty, or the first character is multi-byte, but if the character I want to trim were itself multi-byte, things would get complicated.

The hoop-jumping is needed because both str indexing and comparison (even pattern matching) are behind const trait support, as is str::trim_start_matches. Moreover, str doesn't have a first() or split_first() methods.

I opened an ACP that proposes adding some methods that are in [_] but missing in str.

Also asked on Reddit.

2 posts - 2 participants

Read full topic

🏷️ Rust_feed