rust - Why do I get expected type `()` when trying to obtain a reference to a boxed value? -


i have struct:

pub struct node<t> {     value: t,     left: option<box<node<t>>>,     right: option<box<node<t>>>, }  impl<t> node<t> {     pub fn getleft(&self) -> option<&self> {         if self.left.is_some() {             some(&(*(self.left.unwrap())))             // some(self.left.unwrap()) <= same result         }         none     } }  fn main() {} 

there seems type mismatch error:

error[e0308]: mismatched types   --> src/main.rs:10:13    | 10 |             some(&(*(self.left.unwrap())))    |             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected (), found enum `std::option::option`    |    = note: expected type `()`               found type `std::option::option<&node<t>>` 

i'm new rust , don't understand why expected type () while should option<&self> , how can return reference node inside box (how can move out of borrowed self)?

the problem here isn't borrow-checker. if have if without else, must return unit (i.e. ()). you're trying return value function, means need either have else branch, or use return. wit:

impl<t> node<t> {     pub fn getleft(&self) -> option<&self> {         if self.left.is_some() {             some(&(*(self.left.unwrap())))         } else {             none         }     } } 

ok, now borrow-checker problem. because you're taking reference temporary (the result of self.left.unwrap()). need access contents of option without moving it. let's that:

impl<t> node<t> {     pub fn getleft(&self) -> option<&self> {         if self.left.is_some() {             some(&(*(self.left.as_ref().unwrap())))         } else {             none         }     } } 

that's better, it's ugly. there's unwrap, plus redundant parentheses, name non-idiomatic, , whole branch unnecessary. let's fix of those:

impl<t> node<t> {     pub fn get_left(&self) -> option<&self> {         self.left.as_ref().map(|l| &**l)     } } 

or, if want clearer:

impl<t> node<t> {     pub fn get_left(&self) -> option<&self> {         if let some(left) = self.left.as_ref() {             some(&**left)         } else {             none         }     } } 

Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -