HashMap to Keys error

use std::collections::hash_map::{Keys, HashMap};


#[derive(Debug)]
pub struct TopicNames<'a> {
    //iter: Keys<'a, String, String>,
    
    iter: Keys<'a, u32, u32>,
}

impl<'a> Iterator for TopicNames<'a> {
    //type Item = &'a str;
    type Item = &'a u32;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        //self.iter.next().map(AsRef::as_ref)
        self.iter.next()
    }
}

impl TopicNames<'_>{





    pub fn new(&self) ->TopicNames<'_> { 
    
    let  map = HashMap::from([(1u32, 2u32),]).keys();
    
       TopicNames {iter:map}
        
        
    }
    
    
}



fn main() {
    
}

(Playground)

Errors:

   Compiling playground v0.0.1 (/playground)
error[E0515]: cannot return value referencing temporary value
  --> src/main.rs:32:8
   |
30 |     let  map = HashMap::from([(1u32, 2u32),]).keys();
   |                ------------------------------ temporary value created here
31 |     
32 |        TopicNames {iter:map}
   |        ^^^^^^^^^^^^^^^^^^^^^ returns a value referencing data owned by the current function
   |
   = help: use `.collect()` to allocate the iterator

For more information about this error, try `rustc --explain E0515`.
error: could not compile `playground` due to previous error

You create a temporary hash map here. The hash map is dropped when the function finishes. But you are trying to return a reference to the dropped value (keys() references the original map). This is a dangling pointer, so not possible. Try passing the hash map as argument to your new function. That makes TopicNames valid until the hash map is dropped:

use std::collections::hash_map::{HashMap, Keys};

#[derive(Debug)]
pub struct TopicNames<'a> {
    //iter: Keys<'a, String, String>,
    iter: Keys<'a, u32, u32>,
}

impl<'a> Iterator for TopicNames<'a> {
    //type Item = &'a str;
    type Item = &'a u32;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        //self.iter.next().map(AsRef::as_ref)
        self.iter.next()
    }
}

impl TopicNames<'_> {
    pub fn new(map: &HashMap<u32, u32>) -> TopicNames<'_> {
        TopicNames { iter: map.keys() }
    }
}

fn main() {
    let map = HashMap::from([(1u32, 2u32)]);
    TopicNames::new(&map);
}

Playground.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.