Skip to content
TheChatArchiveThe Chat Archive
gpt-4-0314· openaiHugging Face Suzhen/CodeChat

in rust, how to create a hashset that will be available in all subprojects from which…

  1. User

    in rust, how to create a hashset that will be available in all subprojects from which the project depends and avoid circular dependencies

  2. Assistant

    There isn't really a straightforward way to share a HashSet among multiple sub-projects without creating a circular dependency. However, you can achieve this using an inner shared library or defining a common abstraction.

    Here's a suggestion:

    1. Create a separate shared library within the workspace where you define the shared HashSet.
    2. Add the shared library as a dependency in your sub-projects.
    3. Expose functions to interact with the HashSet in the shared library.

    Now, let's see an example.

    Workspace Cargo.toml:

    [workspace]
    members = [
        "shared",
        "subproj_a",
        "subproj_b",
    ]
    

    shared/Cargo.toml:

    [package]
    name = "shared"
    version = "0.1.0"
    edition = "2018"
    

    shared/src/lib.rs:

    use std::collections::HashSet;
    use std::sync::{Arc, Mutex};
    
    pub struct SharedHashSet(Arc<Mutex<HashSet<String>>>);
    
    impl SharedHashSet {
        pub fn new() -> Self {
            SharedHashSet(Arc::new(Mutex::new(HashSet::new())))
        }
    
        pub fn insert(&self, item: String) {
            self.0.lock().unwrap().insert(item);
        }
    
        pub fn remove(&self, item: &str) {
            self.0.lock().unwrap().remove(item);
        }
    
        pub fn contains(&self, item: &str) -> bool {
            self.0.lock().unwrap().contains(item)
        }
    }
    

    Then, you can use the shared library in your sub-projects:

    subproj_a/Cargo.toml:

    [package]
    name = "subproj_a"
    version = "0.1.0"
    edition = "2018"
    
    [dependencies]
    shared = { path = "../shared" }
    

    subproj_a/src/lib.rs:

    use shared::SharedHashSet;
    
    pub fn subproj_a_function(shared_set: &SharedHashSet) {
        shared_set.insert("Value from subproj_a".to_string());
    }
    

    Similarly, update subproj_b to use the shared library.

    Now, you can create a shared HashSet in your main project and pass it to your sub-projects' functions without causing circular dependencies:

    main.rs:

    use shared::SharedHashSet;
    use subproj_a;
    use subproj_b;
    
    fn main() {
        let shared_set = SharedHashSet::new();
    
        subproj_a::subproj_a_function(&shared_set);
        subproj_b::subproj_b_function(&shared_set);
    
        // Access the shared HashSet
        println!("Contains 'Value from subproj_a': {}", shared_set.contains("Value from subproj_a"));
    }
    

    This way, the shared HashSet is available in all sub-projects and you avoid circular dependencies.