Nathace
Nathace

Reputation: 486

How to use methods of a different struct?

I have a BSTNode struct with an insert function in it:

pub struct BSTNode {
    pub value: i32,
    pub left: Option<Box<BSTNode>>,
    pub right: Option<Box<BSTNode>>,
}

impl BSTNode {
    pub fn insert(&mut self, val: i32) {
        if val <= self.value {
            match self.left {
                None => {
                    self.left = Some(Box::new(BSTNode {
                        value: val,
                        left: None,
                        right: None,
                    }))
                }
                Some(ref mut node) => node.insert(val),
            }
        } else {
            match self.right {
                None => {
                    self.right = Some(Box::new(BSTNode {
                        value: val,
                        left: None,
                        right: None,
                    }))
                }
                Some(ref mut node) => node.insert(val),
            }
        }
    }
}

I also have a BST struct to store that Node

struct BST {
    node: Option<BSTNode>,
}

Is it possible to call the insert func implemented on the BSTNode through the BST struct? What I mean is, that in the main.rs I could do this:

let mut root = BST::BST::new();
root.insert(5) // getting error obviously because method does not exist on BST struct.

Is it possible to kind of point to that BSTNode method what I call 'insert' through the BST struct? I tried to just implement this method in the BST struct instead of keeping it in the BSTNode struct, but I am encountering a lot of problems, although that will be my last resort.

Upvotes: 2

Views: 282

Answers (1)

Silvio Mayolo
Silvio Mayolo

Reputation: 70277

Keep it simple stupid solution: Just make an explicit delegator.

impl BST {

  pub fn insert(&mut self, val: i32) {
    if let Some(node) = self.node.as_mut() {
      node.insert(val);
    }
  }

}

No need to reimplement anything, and the extra function call will almost certainly get inlined out unless you go out of your way to impede optimizations.

Upvotes: 4

Related Questions