首页 > 解决方案 > 如何取消引用 Uuid 类型?

问题描述

我正在使用Uuid crate提供唯一的 id 来实例化Node具有唯一标识符的结构的每个新版本。有时我想过滤这些结构, .contains()以检查结构id是否在某个Vec<Uuid>.

use uuid::Uuid; 

struct Node {
    id: Uuid,
}

impl Node {
    fn new() -> Self {
        let new_obj = Node {
            id: Uuid::new_v4()
        };
        new_obj
    }
    
    fn id(&self) -> Uuid {
        self.id
    }
}

fn main() {
    let my_objs = vec![
        Node::new(), 
        Node::new(), 
        Node::new(), 
        Node::new(), 
    ];
    let some_ids = vec![my_objs[0].id(), my_objs[3].id()];
}

fn filter_objs(all_items: &Vec<Node>, to_get: &Vec<Uuid>){
    for z in to_get {
        let wanted_objs = &all_items.iter().filter(|s| to_get.contains(*s.id()) == true);
    }
}

然而,这给出了错误:

error[E0614]: type `Uuid` cannot be dereferenced
  --> src/main.rs:32:72
   |
32 |         let wanted_objs = &all_items.iter().filter(|s| to_get.contains(*s.id()) == true);
   |                                                                        ^^^^^^^

如何启用Uuid类型的取消引用来解决这个问题?

操场

标签: rustreferenceuuid

解决方案


Uuid没有实现Deref特征,所以它不能被取消引用,也不需要因为你试图将它作为参数传递给期望引用的函数。如果更改*s.id()&s.id()代码编译:

fn filter_objs(all_items: &Vec<Node>, to_get: &Vec<Uuid>) {
    for z in to_get {
        let wanted_objs = &all_items
            .iter()
            // changed from `*s.id()` to `&s.id()` here
            .filter(|s| to_get.contains(&s.id()) == true);
    }
}

操场


推荐阅读