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:
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