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.

RustData Integrity

Code

rustsnippet
18 lines
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 from gets both placeholders swapped in place: find locates each token, start + token.len() bounds the range, and replace_range splices staging and #4211 over the byte ranges without rebuilding the string.

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

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.