Trouble with trait-bound struct


#1

Hello Rust users, I am new to the language itself and am looking to learn more.

Here I have a struct:

#[derive(Debug)]
pub struct PMap<K: Eq + Hash, V>
{
    pub pmap: HashMap<K, V>,  // the property map
    pub elt: V  // default element
}

And a trait ReadWritePropertyMap and it’s implementation for PMap

pub trait ReadPropertyMap
{
    // Using as-yet unspecified associated key-value types
    // one provides upmost genericity
    type Key;
    type Value;

    fn get(&self, key: Self::Key) -> &Self::Value;
}


pub trait ReadWritePropertyMap : ReadPropertyMap
{
    fn put(&mut self, key: Self::Key, val: Self::Value);
}


impl<K, V> ReadPropertyMap for PMap<K, V>
    where K: Ord + Hash
{
    type Key = K;
    type Value = V;

    fn get(&self, key: Self::Key) -> &Self::Value {
        if self.pmap.contains_key(&key) {
            let value = self.pmap.get(&key).unwrap();
            value
        } else {
            &self.elt
        }
    }
}

Although I think that the ReadWriteProperty is defined for this generic struct when I attempt to call the method “put” on a PMap whose concrete type values are integer and string

mod property_map;

fn main ( ) {
    // planet_map maps the volume of a planet (in miles) to it's name
    let mut planet_map: property_map::PMap<i32, &str>;
    planet_map.put(43441, "Jupiter");
}

I receive an error:
no method named put found for type property_map::PMap<i32, &str> in the current scopeat line 7 col 16

What am I missing here? I’ve even tried with a map from i32 to i32 types with the thought that i didn’t implement the trait for reference types like &str but the compiler did not like.


#2

You should import the trait to use its methods.

try

mod property_map;
use property_map::PropertyMap;

fn main ( ) {
    // planet_map maps the volume of a planet (in miles) to it's name
    let mut planet_map: property_map::PMap<i32, &str>;
    planet_map.put(43441, "Jupiter");
}