简体   繁体   English

如何插入 LinkedList 的 HashMap 解引用迭代器?

[英]How to insert into HashMap dereferenced iterator of LinkedList?

How to fix issue on a screenshot?如何解决屏幕截图上的问题? I already tried to make it mutable, but that is not the point.我已经尝试让它可变,但这不是重点。 What can it be, how to get rid of it?它可能是什么,如何摆脱它? I will be thankful for the changes in the code.我将感谢代码中的更改。

screenshot:截屏: scr
(source: i.ibb.co ) (来源: i.ibb.co

let mut buf = vec![0 as u8; 4096];
for stream in listener.incoming() {
    match stream {
        Ok(mut stream) => {
            match stream.read(&mut buf) {
                Ok(size) => {
                    //Get List of names
                    let names: LinkedList<String> = serde_json::from_slice(&buf[..size])?;
                    for name in names.iter() {
                        if (*data).available.contains_key(&*name) {
                            //If file already exist just update Vec of IP
                            (*data)
                                .available
                                .get_mut(&*name)
                                .unwrap()
                                .push(stream.peer_addr().unwrap());
                        } else {
                            //In another case - adding file with first IP that share it
                            let mut v: Vec<SocketAddr> = Vec::new();
                            v.push(stream.peer_addr().unwrap());
                            (*data).available.insert(*name, v);
                        }
                    }
                }
                Err(_) => {
                    println!("An error occurred, {}", stream.peer_addr().unwrap());
                }
            }
        }
        Err(e) => {
            println!("Error: {}", e);
        }
    }
}

Are you sure you want a LinkedList and not a Vec as output from your JSON parser?您确定要来自 JSON 解析器的LinkedList而不是Vec作为 output 吗? From the LinkedList docs:来自LinkedList文档:

It is almost always better to use Vec or VecDeque because array-based containers are generally faster, more memory efficient, and make better use of CPU cache.使用VecVecDeque几乎总是更好,因为基于数组的容器通常更快,memory 效率更高,并且更好地利用 CPU 缓存。

To solve your problem, you should loop over names instead of names.iter() .要解决您的问题,您应该遍历names而不是names.iter() This will make the list unusable after the for loop.这将使列表在for循环后无法使用。 You will then have to remove the dereferences in your code, ie write &name instead of " &*name " and name instead of *name .然后,您必须删除代码中的取消引用,即用&name代替“ &*name ”,用name代替*name However, you shouldn't have written &*name at all because the & and * in &*name are cancelling each other out.但是,您根本不应该写&*name ,因为 &* &*name中的&*相互抵消。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM