Multiple Borrows Error For simple application

I have been trying to learn Rust by developing small programs, however the learning curve is more steep than I thought.

I have been playing with the following code snippet which does not work because of a borrowing compiler error.

It’s a simple program, in which you have a dictionary of custom objects. Based on some conditions, some values will be mutated, whilst others will be deleted from the dictionary.

use std::collections::HashMap;

// Define the Custom struct
pub struct Custom {
    x: u8,
}

fn main() {
    // Create a HashMap with string keys and Custom objects as values
    let mut custom_map: HashMap<String, Custom> = HashMap::new();

    // Insert some sample data into the map
    custom_map.insert("apple".to_string(), Custom { x: 10 });
    custom_map.insert("banana".to_string(), Custom { x: 20 });
    custom_map.insert("grape".to_string(), Custom { x: 30 });
    custom_map.insert("quince".to_string(), Custom { x: 40 }); // Example entry with 'q'

    let mut elements_to_be_deleted: Vec<&String> = Vec::new();

    // Iterate over the keys and values in the map
    for (key, custom) in &mut custom_map {
        if key.contains('a') {
            // Increment the x property for keys containing 'a'
            custom.x += 1;
        }

        if key.contains('q') {
            // Remove entries with 'q' from the map
            elements_to_be_deleted.push(key);
        }
    }

    // iterate over the keys that need to be deleted
    for key in &elements_to_be_deleted {
        custom_map.remove(*key);
    }

    // Print the updated values
    for (key, custom) in &custom_map {
        println!("Key: {}, x: {}", key, custom.x);
    }
}

The compiler error is the following:

   |
21 |     for (key, custom) in &mut custom_map {
   |                          --------------- first mutable borrow occurs here

34 |     for key in &elements_to_be_deleted {
   |                ----------------------- first borrow later used here
35 |         custom_map.remove(*key);
   |         ^^^^^^^^^^ second mutable borrow occurs here

Ok, I understand, I cannot have both the mutable variable itself and a mutable reference to it in the same lifecycle.

I changed the above code and offloaded the mutation operations in separate functions

use std::collections::HashMap;

// Define the Custom struct
pub struct Custom {
    x: u8,
}

fn main() {
    // Create a HashMap with string keys and Custom objects as values
    let mut custom_map: HashMap<String, Custom> = HashMap::new();

    // Insert some sample data into the map
    custom_map.insert("apple".to_string(), Custom { x: 10 });
    custom_map.insert("banana".to_string(), Custom { x: 20 });
    custom_map.insert("grape".to_string(), Custom { x: 30 });
    custom_map.insert("quince".to_string(), Custom { x: 40 }); // Example entry with 'q'

    let mut elements_to_be_deleted: Vec<&String> = Vec::new();

    // Iterate over the keys and values in the map
    for (key, custom) in &custom_map {
        if key.contains('q') {
            // Remove entries with 'q' from the map
            elements_to_be_deleted.push(&key);
        }
    }

    // modify map elements
    modifyMapElements(&mut custom_map);

    //delete map elements
    deleteElementsFromMap(&mut custom_map, elements_to_be_deleted);

    // Print the updated values
    for (key, custom) in &custom_map {
        println!("Key: {}, x: {}", key, custom.x);
    }
}

fn deleteElementsFromMap(map: &mut HashMap<String, Custom>, els_to_delete: Vec<&String>) {
    for key in elements_to_be_deleted {
        map.remove(&key);
    }
}

fn modifyMapElements(map: &mut HashMap<String, Custom>) {
    for (key, custom) in map {
        if key.contains('a') {
            // Increment the x property for keys containing 'a'
            custom.x += 1;
        }
    }
}

The compiler error for this snippet is this:

   for (key, custom) in &custom_map {
   |                          ----------- immutable borrow occurs here
...
32 |     deleteElementsFromMap(&mut custom_map, elements_to_be_deleted);
   |                           ^^^^^^^^^^^^^^^  ---------------------- immutable borrow later used here
   |                           |
   |                           mutable borrow occurs here

I have tried enclosing the for loop which iterates immutably over the map in a separate block, but it solves nothing

    {
        // Iterate over the keys and values in the map
        for (key, custom) in &custom_map {
            if key.contains('q') {
                // Remove entries with 'q' from the map
                elements_to_be_deleted.push(&key);
            }
        }
    }

I get it, you cannot have mutable and immutable references for a variable on the same scopes.

My question is, how to design the code above to use the Rust reference system to my advantage ?
I am more interested in learning how to think and design this piece of code as a Rust developer, so I wouldn’t be particularily interested in workarounds.

New contributor

theAsker is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật