camel To snake Identifier Rewrites
Rewrite camelCase identifiers to snake_case by scanning chars and inserting an underscore before each uppercase letter.
Code
// 逐字符扫描:遇到大写字母先补下划线再转小写
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
Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.GraphQL SDL to TypeScript ConverterParse GraphQL SDL type, input, interface, enum, union, and scalar definitions into strict TypeScript interfaces and literal unions locally.JSON to TypeScriptGenerate TypeScript interface and type declarations from a sample JSON payload, inferring primitives, arrays, and nested object shapes automatically.
FAQ
- How do you run camel To snake Identifier Rewrites?
- The file is self-contained: run it directly, no dependencies to install beforehand.
Report a problem with this exampleOpens a pre-filled issue on GitHub.