gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 11:36:15 25 4
gpt4 key购买 nike

我正在使用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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com