Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,699 questions

57,016 answers

573 users

How to get and use a hash code for an array and a vector of integers in Rust

1 Answer

0 votes
use std::hash::{Hash, Hasher};
use std::collections::hash_map::DefaultHasher;

pub struct ArrayHashHelper;

impl ArrayHashHelper {

    pub fn get_array_hash_code(values: Option<&[i32]>) -> i32 {
        // Handle null input.
        let values = match values {
            Some(v) => v,
            None => return 0,
        };

        // HashCode provides a high-quality hash implementation.
        let mut hasher = DefaultHasher::new();

        // Add each element in order.
        // Order matters: [1,2,3] != [3,2,1].
        values.hash(&mut hasher);

        // Convert u64 hash to i32 to match the C# return type
        hasher.finish() as i32
    }

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

        let hash_code = ArrayHashHelper::get_array_hash_code(Some(&numbers));

        println!("{}", hash_code);

        let array1 = [1, 2, 3];
        let array2 = [1, 2, 3];

        let hash1 = ArrayHashHelper::get_array_hash_code(Some(&array1));
        let hash2 = ArrayHashHelper::get_array_hash_code(Some(&array2));

        if hash1 == hash2 {
            println!("Arrays may be equal.");
        }

        if hash1 == hash2 && array1 == array2 {
            println!("Arrays are equal.");
        }
    }
}

fn main() {
    ArrayHashHelper::main();
}


/*
run:

-1606495798
Arrays may be equal.
Arrays are equal.

*/

 



answered 2 days ago by avibootz
...