Last active
March 18, 2020 17:13
-
-
Save kyleheadley/dbc2469182c61eedb481fc034a55223f to your computer and use it in GitHub Desktop.
demo a struct that can be used with Rc or Arc pointer types
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::ops::Deref; | |
use std::rc::Rc; | |
use std::sync::Arc; | |
trait PtrFunc<A> {type Ptr:Sized+Clone+Deref+From<A>;} | |
struct RcPtr; | |
impl<A> PtrFunc<A> for RcPtr {type Ptr = Rc<A>;} | |
struct ArcPtr; | |
impl<A> PtrFunc<A> for ArcPtr {type Ptr = Arc<A>;} | |
struct TreeNode<T, P> where | |
P : PtrFunc<TreeNode<T,P>>, | |
{ | |
val: T, | |
right: Option<P::Ptr>, | |
left: Option<P::Ptr>, | |
} | |
type RcTree = TreeNode<i32,RcPtr>; | |
type ArcTree = TreeNode<i32,ArcPtr>; | |
fn main() { | |
let rt: RcTree = TreeNode{ | |
val:2, | |
right:Some(Rc::new(TreeNode{ | |
val:5, | |
right:None, | |
left:None, | |
})), | |
left:Some(Rc::new(TreeNode{ | |
val:1, | |
right:None, | |
left:None, | |
})), | |
}; | |
let at: ArcTree = TreeNode{ | |
val:4, | |
right:Some(Arc::new(TreeNode{ | |
val:1, | |
right:None, | |
left:None, | |
})), | |
left:Some(Arc::new(TreeNode{ | |
val:6, | |
right:None, | |
left:None, | |
})), | |
}; | |
println!("The top values are"); | |
println!("{} and {}", rt.val, at.val); | |
println!("The right values are"); | |
println!("{} and {}", rt.right.unwrap().val, at.right.unwrap().val); | |
println!("The left values are"); | |
println!("{} and {}", rt.left.unwrap().val, at.left.unwrap().val); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment