Passing imp DS(vec,map,set) to function

In Rust, we can pass imp data structures such as Vec<T>, HashMap<K, V>, and HashSet<T> to functions in different ways, depending on whether you want to:

  1. Pass by ownership (move the value into the function).
  2. Pass by immutable reference (&T) (allow the function to read the value).
  3. Pass by mutable reference (&mut T) (allow the function to modify the value).


1. Passing a Vec<T> (Vector)

A vector (Vec<T>) is a growable array type.

// Takes ownership and moves the vector.
fn take_vector(vec: Vec<i32>) {
    println!("Vector moved into function: {:?}", vec);
}

//  Takes an immutable reference.
fn borrow_vector(vec: &Vec<i32>) {
    println!("Borrowed vector: {:?}", vec);
}

// Takes a mutable reference and modifies the vector.
fn modify_vector(vec: &mut Vec<i32>) {
    vec.push(108);
    println!("Modified vector: {:?}", vec);
}

fn main() {
    let mut numbers = vec![1, 2, 3];

    take_vector(numbers.clone());  // Pass ownership (move) but cloning to retain the original
    borrow_vector(&numbers);       // Pass by immutable reference
    modify_vector(&mut numbers);   // Pass by mutable reference

    println!("Vector after modification: {:?}", numbers);
}

/*
Vector moved into function: [1, 2, 3]
Borrowed vector: [1, 2, 3]
Modified vector: [1, 2, 3, 108]
Vector after modification: [1, 2, 3, 42]
*/        

2. Passing a HashMap<K, V> (Key-Value Map)

A HashMap<K, V> is a collection of key-value pairs.

use std::collections::HashMap;

fn take_map(map: HashMap<String, i32>) {
    println!("Map moved into function: {:?}", map);
}

fn borrow_map(map: &HashMap<String, i32>) {
    println!("Borrowed map: {:?}", map);
}

fn modify_map(map: &mut HashMap<String, i32>) {
    map.insert("d".to_string(), 40);
    println!("Modified map: {:?}", map);
}

fn main() {
    let mut scores = HashMap::new();
    scores.insert("a".to_string(), 10);
    scores.insert("b".to_string(), 20);
    scores.insert("c".to_string(), 30);

    take_map(scores.clone());  // Pass by value (move), cloning to retain the original
    borrow_map(&scores);       // Pass by immutable reference
    modify_map(&mut scores);   // Pass by mutable reference

    println!("Map after modification: {:?}", scores);
}
/*
Map moved into function: {"a": 10, "b": 20, "c": 30}
Borrowed map: {"a": 10, "b": 20, "c": 30}
Modified map: {"a": 10, "b": 20, "d": 40, "c": 30}
Map after modification: {"a": 10, "b": 20, "d": 40, "c": 30}
*/        

3. Passing a HashSet<T> (Set)

A HashSet<T> is a collection of unique values.

use std::collections::HashSet;

fn take_set(set: HashSet<i32>) {
    println!("Set moved into function: {:?}", set);
}

fn borrow_set(set: &HashSet<i32>) {
    println!("Borrowed set: {:?}", set);
}

fn modify_set(set: &mut HashSet<i32>) {
    set.insert(108);
    println!("Modified set: {:?}", set);
}

fn main() {
    let mut numbers: HashSet<i32> = vec![1, 2, 3].into_iter().collect();

    take_set(numbers.clone());  // Pass by value (move), cloning to retain the original
    borrow_set(&numbers);       // Pass by immutable reference
    modify_set(&mut numbers);   // Pass by mutable reference

    println!("Set after modification: {:?}", numbers);
}
/*
Set moved into function: {1, 3, 2}
Borrowed set: {1, 3, 2}
Modified set: {1, 2, 108, 3}
Set after modification: {1, 2, 108, 3}
*/        

要查看或添加评论,请登录

Amit Nadiger的更多文章

  • Atomics in C++

    Atomics in C++

    The C++11 standard introduced the library, providing a way to perform operations on shared data without explicit…

    1 条评论
  • List of C++ 11 additions

    List of C++ 11 additions

    Smart Pointers Types: std::unique_ptr, std::shared_ptr, and std::weak_ptr. Purpose: Smart pointers manage dynamic…

    2 条评论
  • std::lock, std::trylock in C++

    std::lock, std::trylock in C++

    std::lock - cppreference.com Concurrency and synchronization are essential aspects of modern software development.

    2 条评论
  • std::unique_lock,lock_guard, & scoped_lock

    std::unique_lock,lock_guard, & scoped_lock

    C++11 introduced several locking mechanisms to simplify thread synchronization and prevent race conditions. Among them,…

  • Understanding of virtual & final in C++ 11

    Understanding of virtual & final in C++ 11

    C++ provides powerful object-oriented programming features such as polymorphism through virtual functions and control…

  • Importance of Linux kernal in AOSP

    Importance of Linux kernal in AOSP

    The Linux kernel serves as the foundational layer of the Android Open Source Project (AOSP), acting as the bridge…

    1 条评论
  • AOSP

    AOSP

    AOSP stands for the Android Open Source Project. Its the foundation of the Android operating system.

  • Creating a String from a string literal (&str)

    Creating a String from a string literal (&str)

    Different methods to create a from a string literal () are as follows : 1. to_owned() The to_owned() method is a…

  • Reducing the size of Rust Executables

    Reducing the size of Rust Executables

    First of all why are Rust Executables Large? Debug Symbols: By default, Rust includes debug symbols in the binary for…

  • Rust Stream

    Rust Stream

    In Rust, streams are a core part of asynchronous programming, commonly used to handle sequences of values produced…