Avatar ·

How to correctly concatenate two vectors (Vec) in Rust? Best ways to concatenate

Hello everyone! I just started learning Rust and encountered a task of concatenating two vectors. Let's say I have two vectors of numbers: `vec1` and `vec2`. I need to get a third vector that contains all elements from the first one, and then all from the second one. In Python I would just write `vec1 + vec2`, but in Rust this doesn't work. I tried several approaches, but I'm not sure which one is correct and efficient. Here's my code: ```rust let mut vec1 = vec![1, 2, 3]; let vec2 = vec![4, 5, 6]; // Attempt 1: simple addition (doesn't compile) // let result = vec1 + vec2; // Attempt 2: using extend vec1.extend(vec2); println!("{:?}", vec1); // Got [1, 2, 3, 4, 5, 6], but vec1 was modified // Attempt 3: using a loop let mut result = Vec::new(); for item in &vec1 { result.push(*it