Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to create a `HashMap` keyed by something of type `*const Any`?

Tags:

hashmap

rust

This code

use std::any::Any;
use std::collections::HashMap;

fn main() {
    let x: HashMap<*const Any, i32> = HashMap::new();
}

Gives me the following error:

error: the trait `core::marker::Sized` is not implemented for the type `core::any::Any` [E0277]

let x: HashMap<*const Any, i32> = HashMap::new();
                                  ^~~~~~~~~~~~

First of all, I don't understand why it is complaining about core::any::Any, when the keys are of type *const core::any::Any. Shouldn't *const _ be sized regardless of what it is pointing to? To test this, I tried:

use std::any::Any;
use std::mem::size_of;

fn main() {
    println!("size_of(*const Any) = {}", size_of::<*const Any>());
}

Which, as expected, produces:

size_of(*const Any) = 16
like image 950
Matt Avatar asked Feb 23 '16 00:02

Matt


People also ask

How does a Hashmap work rust?

Hashmap in rust is a structure which comprises of the look-up table and data in it in form of key and value pair which will be used for storing and retrieving data continuously. Hashmap needs to be explicitly imported from the rust inbuilt library collection before that can be used within the program.


1 Answers

It's not the prettiest solution, but here is what I came up with:

use std::any::Any;
use std::collections::HashMap;
use std::hash::{Hasher, Hash};
use std::cmp;

struct Wrapper {
    v: *const Any,
}

impl Wrapper {
    fn get_addr(&self) -> usize {
        self.v as *const usize as usize
    }
}

impl Hash for Wrapper {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.get_addr().hash(state)
    }
}

impl cmp::PartialEq for Wrapper {
    fn eq(&self, other: &Self) -> bool {
        self.get_addr() == other.get_addr()
    }
}

impl cmp::Eq for Wrapper {}

fn main() {
    let x: HashMap<Wrapper, i32> = HashMap::new();
}
like image 89
Matt Avatar answered Oct 19 '22 12:10

Matt