camel To snake Identifier Rewrites

Rewrite camelCase identifiers to snake_case by scanning chars and inserting an underscore before each uppercase letter.

RustCli Tooling

Code

rustsnippet
17 lines
// 逐字符扫描:遇到大写字母先补下划线再转小写
fn camel_to_snake(input: &str) -> String {
    let mut out = String::with_capacity(input.len() + 4);
    for (index, ch) in input.chars().enumerate() {
        if index > 0 && ch.is_ascii_uppercase() {
            out.push('_');
        }
        out.extend(ch.to_lowercase());
    }
    out
}

fn main() {
    for name in ["batchSize", "httpTimeoutMs", "already_snake", "ID"] {
        println!("{name} -> {}", camel_to_snake(name));
    }
}

What the code does

The code’s whole job belongs to the functions camel_to_snake and main.

The cycling part of this snippet is for (index, ch) in input.chars().enumerate().

Caveats

  • Import targets, if present, are standard-library modules only.

Using it

Entry signature: fn camel_to_snake(input: &str) -> String

The sequence camel_to_snake lives in main; running the file triggers it.

Key statements

fn camel_to_snake(input: &str) -> String {
    let mut out = String::with_capacity(input.len() + 4);
    for (index, ch) in input.chars().enumerate() {
        if index > 0 && ch.is_ascii_uppercase() {
            out.push('_');
        }
        out.extend(ch.to_lowercase());
    }
    out
}

Interactive Tools for This Topic

FAQ

How do you run camel To snake Identifier Rewrites?
The file is self-contained: run it directly, no dependencies to install beforehand.