Repeat Own Prefix With extend_from_within

Clone a range of a Vec onto its own end with extend_from_within, which reads the source range before growing so repeats need no temporary buffer.

RustData Integrity

Code

rustsnippet
23 lines
fn main() {
    let mut pattern = vec![1u8, 2, 3];
    println!("start: {:?} len={}", pattern, pattern.len());

    // 把自己的全部内容追加一遍
    pattern.extend_from_within(..);
    println!("doubled: {:?} len={}", pattern, pattern.len());

    // 只追加其中一段:先按索引取出,再补到末尾
    pattern.extend_from_within(2..4);
    println!("with tail: {:?} len={}", pattern, pattern.len());

    let mut ring = vec!['a', 'b', 'c'];
    ring.extend_from_within(1..);
    println!("ring: {:?} cap={}", ring, ring.capacity());

    // 区间越界会 panic,调用前校验起点
    let start = 1;
    if start < pattern.len() {
        pattern.extend_from_within(start..start + 1);
    }
    println!("final: {:?}", pattern);
}

Inside the snippet

Repeat Own Prefix With extend_from_within reduces to the function main.

Watch out for

  • There is no dependency tree here — the platform is the whole dependency.

Putting it to use

The primary signature is fn main()

Output lines are prefixed (start:, doubled:, with tail:), making each step’s effect easy to spot.

Core lines

pattern.extend_from_within(start..start + 1);
let mut ring = vec!['a', 'b', 'c'];
let mut pattern = vec![1u8, 2, 3];

Interactive Tools for This Topic

FAQ

What does Repeat Own Prefix With extend_from_within print when run?
Invoke the file as-is — the `start:`, `doubled:`, `with tail:` prefixes identify which step printed each line.