Vec::extend with return of vector

Dear rust-pros,

I'm looking for a Vec::extend method that returns the result. Currently I have stuff like:

// These are vectors returned from method calls
let a = vec![1,2];
let b = vec![3,4];
// The method returns a Vec

But I would like to be able to do something like:

// The vec![] are method calls

Is there such a method on Vec? Of course I could do


But that feels as bad as the extend...

There's Vec::append that modifies the vector in-place, and destroys its argument.

If you're after saving a line of code through methods returning the vector itself, you won't find them.

This is because Rust has single ownership — a non-copyable object like Vec can exist in one place at a time, only. A method like can't return foo without also unconditionally destroying the foo variable. So methods are either designed to always move self (like .into()) or perform modification in place without returning self, but optional chaining doesn't work well with Rust's semantics.

1 Like

Nice answer, thanks. But something like this should be rusty, no?

let a = vec![1,2];
let b = vec![3,4];
// Return the concatenated vector
Vec::concat(a, b)

as it could consume the a and b. Is there such a static method?

It's { vec_a.append(&mut vec_b); vec_a } :slight_smile:

Generally speaking, the standard library does not provide both &mut T and T -> T versions of a function. Off the top of my head I can't even think of any examples where it has provided both, unless you count operators. It typically prefers to expose the &mut T version as this is more versatile.

I generally begin with writing something like

let a = {
    let mut a = func_1();

and in particularly egregious cases where the block expressions detract significantly from readibility, I define a helper function.

There's concat([a, b]) from itertools:

1 Like

Cool! Thanks a lot. This is what I was looking for.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.