Rust Program to Merge two lists


Merge two lists

Rust Programming Language


Merge two lists


Problem


Rust program that merges two lists.

Input


fn main() {
    let list1 = vec![1, 2, 3];
    let list2 = vec![4, 5, 6];
    
    let merged_list = merge_lists(&list1, &list2);
    
    println!("Merged list: {:?}", merged_list);
}

fn merge_lists(list1: &[i32], list2: &[i32]) -> Vec<i32> {
    let mut merged = vec![];
    
    for &item in list1 {
        merged.push(item);
    }
    
    for &item in list2 {
        merged.push(item);
    }
    
    merged
}{codeBox}

Output


Merged list: [1, 2, 3, 4, 5, 6]{codeBox}

Explanation


In this example, we define two lists (list1 and list2) using Rust's vec type. Then, we call a function called merge_lists to merge the two lists. The merge_lists function takes two slices of i32 (the type of the items in the lists) as arguments and returns a new Vec<i32> containing the merged elements.

The merge_lists function creates a new, empty Vec<i32> called merged. It then loops through each item in list1 and adds it to merged using the push method. It does the same thing for list2. Finally, it returns the merged Vec<i32>.

When we call merge_lists with &list1 and &list2, we pass references to the two lists rather than the lists themselves. This is because we want to avoid moving or copying the data in the lists unnecessarily.



Post a Comment