Replace Range Rewrites String Segments
replace_range swaps any byte-range of a String for new text in place, so placeholder tokens of different lengths can be rewritten without rebuilding the string.
Code
fn main() {
let mut template = String::from("deploy <env> from <build>");
// replace_range rewrites byte-range segments in place
let start = template.find("<env>").unwrap();
let end = start + "<env>".len();
template.replace_range(start..end, "staging");
println!("{template}");
let start = template.find("<build>").unwrap();
let end = start + "<build>".len();
template.replace_range(start..end, "#4211");
println!("{template}");
// the new text length need not match the replaced range
template.replace_range(7..14, "prod"); // replaces "staging"
println!("{template}");
}What the demo rewrites
The template deploy
The final edit changes lengths deliberately: replace_range(7..14, “prod”) swaps the seven-char staging for the four-char prod, printing deploy prod from #4211. Byte ranges, not char counts, are the unit, so all inputs here stay ASCII-safe.
Points worth noting
- find returns byte offsets, which is exactly what replace_range consumes.
- The call panics if the range does not land on char boundaries.
Interactive Tools for This Topic
SemVer Range CheckerCheck whether a semantic version satisfies an npm-style range such as caret, tilde, comparison sets, wildcards, or hyphen ranges.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- Does the replacement need to match the removed length?
- No; replace_range resizes in place. The demo swaps 7 bytes for 4 in the final edit and prints the shortened result.
Report a problem with this exampleOpens a pre-filled issue on GitHub.