Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
292 views
in Technique[技术] by (71.8m points)

rust - How to dereference Uuid type?

I'm using the Uuid crate to give unique ids to instantiate each new version of a Node struct with a unique identifier. Sometimes I'd like to filter these structs using .contains() to check if a struct's id is inside some array of 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);
    }
}

However this gives the error:

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

How can I enable dereferencing for the Uuid type to solve this problem?

Playground

question from:https://stackoverflow.com/questions/65877812/how-to-dereference-uuid-type

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Uuid doesn't implement the Deref trait so it can't be dereferenced, nor does it need to be since you're trying to pass it as an argument to a function with expects a reference. If you change *s.id() to &s.id() the code compiles:

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...