Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0613· OpenAIAi2 WildChat-4.8M (AI2)

rust hashset to vec

  1. User

    rust hashset to vec

  2. Assistant

    To convert a HashSet to a Vec in Rust, you can use the collect method with the appropriate types. Here's an example:

    use std::collections::HashSet;
    
    fn main() {
        let hash_set: HashSet<i32> = [1, 2, 3, 4, 5].iter().cloned().collect();
        let vec: Vec<i32> = hash_set.into_iter().collect();
    
        println!("{:?}", vec);
    }
    

    In this example, we first create a HashSet called hash_set and initialize it with some values using the collect method. Then, we convert the HashSet to a Vec by calling into_iter on the HashSet and then using collect to collect the values into a Vec. Finally, we print the resulting Vec to verify the conversion.

    Note that the HashSet does not guarantee a specific order for its elements, so the resulting Vec may not preserve the original order of the HashSet elements. If you need to maintain the order, you can use a different data structure, such as BTreeSet, which provides a sorted order.