Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use std::error::Error;
- use refbox::{RefBox, Ref};
- struct Node<T> {
- id: T,
- left: Option<RefBox<Node<T>>>,
- right: Option<RefBox<Node<T>>>,
- }
- trait MapRefBox<T> {
- fn map_to_ref(&self) -> Option<Ref<T>>;
- }
- impl<T> MapRefBox<T> for Option<RefBox<T>> {
- fn map_to_ref(&self) -> Option<Ref<T>> {
- self.as_ref().map(|rc| rc.create_ref())
- }
- }
- fn node(id: i32, l: RefBox<Node<i32>>, r: RefBox<Node<i32>>) -> RefBox<Node<i32>> {
- RefBox::new(Node { id, left: Some(l), right: Some(r) })
- }
- fn left(id: i32, l: RefBox<Node<i32>>) -> RefBox<Node<i32>> {
- RefBox::new(Node { id, left: Some(l), right: None })
- }
- fn right(id: i32, r: RefBox<Node<i32>>) -> RefBox<Node<i32>> {
- RefBox::new(Node { id, left: None, right: Some(r) })
- }
- fn leaf(id: i32) -> RefBox<Node<i32>> {
- RefBox::new(Node { id, left: None, right: None })
- }
- // immutable access to tree
- fn print_tree(node: Option<Ref<Node<i32>>>, depth: usize) -> Result<(), Box<dyn Error>> {
- if let Some(n) = node {
- let n = n.try_borrow_mut()?;
- println!("{}{}", " ".repeat(depth), n.id);
- print_tree(n.left.map_to_ref(), depth + 1)?;
- print_tree(n.right.map_to_ref(), depth + 1)?;
- }
- Ok(())
- }
- fn main() -> Result<(), Box<dyn Error>> {
- let tree = node(1,
- node(2, leaf(4), leaf(5)),
- node(3, leaf(6), leaf(7)));
- print_tree(Some(tree).map_to_ref(), 0)?;
- println!("Hello, world!");
- Ok(())
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement