Skip to content

Instantly share code, notes, and snippets.

@kyleheadley
Last active March 18, 2020 17:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kyleheadley/dbc2469182c61eedb481fc034a55223f to your computer and use it in GitHub Desktop.
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
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