Concatenate vectors of strings (merge vectors, join vectors)

concat vec! clone

examples/concatenate-vectors-of-string/src/main.rs

macro_rules! prt {
    ($var:expr) => {
        println!("{:p}, {:?} {:?}", &$var, &$var.as_ptr(), &$var[0].as_ptr());
    };
}

fn main() {
    concat();
    concat_and_use();
}

fn concat() {
    let birds = vec![String::from("turkey"), String::from("duck")];
    let mammals = vec![String::from("cow"), String::from("horse")];
    let fishes = vec![String::from("salmon"), String::from("cod")];
    dbg!(&birds);
    dbg!(&mammals);
    dbg!(&fishes);

    prt!(birds);
    prt!(mammals);
    prt!(fishes);

    let animals = [birds, mammals, fishes].concat();
    dbg!(&animals);
    prt!(animals);
}

fn concat_and_use() {
    let birds = vec![String::from("turkey"), String::from("duck")];
    let mammals = vec![String::from("cow"), String::from("horse")];
    let fishes = vec![String::from("salmon"), String::from("cod")];

    let animals = [birds.clone(), mammals, fishes].concat();
    dbg!(animals);
    dbg!(&birds);
}

// concatenate vectors - merge vectors, join vectors together

In the first example (the concat function) we simply join the vectors together using the concat method. In this example we don't try to use the original vectors after the concatenation.

In the second example (the concat_and_use function) we want to use one of the original vectors after we concatenated them. This creates a compilation errro:

borrow of moved value: `birds`

and the compler suggests the use of the clone to copy the content of the vector. This solves the problem.

Author

Gabor Szabo (szabgab)

Gabor Szabo, the author of the Rust Maven web site maintains several Open source projects in Rust and while he still feels he has tons of new things to learn about Rust he already offers training courses in Rust and still teaches Python, Perl, git, GitHub, GitLab, CI, and testing.

Gabor Szabo