Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Function returns &Option and not Option

I am a beginner in Rust and I don’t understand the behaviour I am encountering. Function number 1 should return me an Option type but returns an &Option type. I have worked around this by doing function 2 but I don’t understand why this works. What am I doing wrong in my function?

Function 1:

pub fn manage_request(&self, request:String) -> Option<Some type> {
    let words : Vec<&str> = request.split_whitespace().collect();
    match words[0] {
        "attach" => &self.hashmap.get(words[1]),
        _ => None,
    }
}

Function 2:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

pub fn manage_request(&self, request:String) -> Option<Some type> {
    let words : Vec<&str> = request.split_whitespace().collect();
    match words[0] {
        "attach" => match &self.hashmap.get(words[1]){
            None => None,
            Some(x) => Some(x)
        }
        _ => None,
    }
}

Here is a link to rust playground with the code

>Solution :

Correct me if Im wrong but I think you actually did this properly but might have missed a typo.

In your playground your signature consumes self by saying fn manage_request(self). If you change this to take a reference to self like fn manage_request(&self) I believe it works.

Updated playground link runs without compiler errors: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=a5a104cc02f1f4715f4420a8ff6da1f8

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading