@@ -81,7 +81,7 @@ impl<T, N: Node<T, Ix>, Ix: IndexType> Tree<T, N, Ix> {
8181 /// # Returns
8282 /// - `Ok(&N)` if a root exists.
8383 /// - `Err(TreeError::MissingRoot)` if the tree has no root.
84- pub fn try_root ( & self ) -> Result < & N , TreeError < Ix > > {
84+ pub fn try_root ( & self ) -> Result < & N , TreeError > {
8585 if let Some ( idx) = self . root {
8686 Ok ( & self . nodes [ idx. index ( ) ] )
8787 } else {
@@ -92,6 +92,14 @@ impl<T, N: Node<T, Ix>, Ix: IndexType> Tree<T, N, Ix> {
9292 }
9393 }
9494
95+ /// Returns a reference to an element [`Node`] or subslice depending on the type of index.
96+ pub fn get < I > ( & self , idx : I ) -> Option < & <I as SliceIndex < [ N ] > >:: Output >
97+ where
98+ I : SliceIndex < [ N ] > ,
99+ {
100+ self . nodes . get ( idx)
101+ }
102+
95103 /// Push nodes onto [`Tree`] node list without connection.
96104 ///
97105 /// Return there [`NodeIndex`] within the tree
@@ -225,6 +233,25 @@ mod test {
225233 assert ! ( tree_iter. next( ) . is_none( ) ) ;
226234 }
227235
236+ #[ test]
237+ fn test_tree_get ( ) {
238+ let mut root: Node < String > = Node :: new ( "hello" . to_string ( ) ) ;
239+ root. children = vec ! [ NodeIndex :: new( 1 ) , NodeIndex :: new( 2 ) ] ;
240+ let mut tree: Tree < String > = Tree :: new ( ) ;
241+ let n1 = Node :: new ( "world" . to_string ( ) ) ;
242+ let n2 = Node :: new ( "!" . to_string ( ) ) ;
243+ tree. root = Some ( NodeIndex :: new ( 0 ) ) ;
244+ tree. nodes . push ( root. clone ( ) ) ;
245+ tree. nodes . push ( n1. clone ( ) ) ;
246+ tree. nodes . push ( n2. clone ( ) ) ;
247+
248+ if let Some ( output) = tree. get ( ..) {
249+ assert_eq ! ( root, output[ 0 ] ) ;
250+ assert_eq ! ( n1, output[ 1 ] ) ;
251+ assert_eq ! ( n2, output[ 2 ] ) ;
252+ }
253+ }
254+
228255 #[ test]
229256 fn test_tree_subtree ( ) {
230257 let mut root: Node < String > = Node :: new ( "hello" . to_string ( ) ) ;
0 commit comments