rust - 如何取消引用 Uuid 类型?

标签 rust reference 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 的取消引用输入来解决这个问题?

Playground

最佳答案

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);
    }
}

playground

关于rust - 如何取消引用 Uuid 类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65877812/

相关文章:

python - 根据第三个列表中的随机项目,从两个列表之一中选择一个随机项目

c++ - 使用行为不同的引用返回 tmp

c - 使用 libblkid 时出错

rust - 使用 nom 匹配模板过滤器表达式

rust - 如何在 Rust 中的不同 Future 特征之间创建互操作性?

rust - 火箭整流罩、tokio-scheduler 和 cron 的生命周期问题

java - java.lang.Long 或 java.util.UUID 是安全的共享 secret 吗?

rust - 如何读取 HttpRequest 正文

javascript - 以下 Javascript 函数是按值还是按引用传递参数?我不确定如何区分两者

node.js - 在 Gulp 3.9.1 中的管道之间传递变量