@@ -17,6 +17,42 @@ pub enum List<T> {
17
17
Nil ,
18
18
}
19
19
20
+ pub struct Items < ' a , T > {
21
+ priv head : & ' a List < T > ,
22
+ priv next : Option < & ' a @List < T > >
23
+ }
24
+
25
+ impl < ' a , T > Iterator < & ' a T > for Items < ' a , T > {
26
+ fn next ( & mut self ) -> Option < & ' a T > {
27
+ match self . next {
28
+ None => match * self . head {
29
+ Nil => None ,
30
+ Cons ( ref value, ref tail) => {
31
+ self . next = Some ( tail) ;
32
+ Some ( value)
33
+ }
34
+ } ,
35
+ Some ( next) => match * * next {
36
+ Nil => None ,
37
+ Cons ( ref value, ref tail) => {
38
+ self . next = Some ( tail) ;
39
+ Some ( value)
40
+ }
41
+ }
42
+ }
43
+ }
44
+ }
45
+
46
+ impl < T > List < T > {
47
+ /// Returns a forward iterator
48
+ pub fn iter < ' a > ( & ' a self ) -> Items < ' a , T > {
49
+ Items {
50
+ head : self ,
51
+ next : None
52
+ }
53
+ }
54
+ }
55
+
20
56
/**
21
57
* Left fold
22
58
*
@@ -181,6 +217,16 @@ mod tests {
181
217
182
218
use std:: option;
183
219
220
+ #[ test]
221
+ fn test_iter ( ) {
222
+ let list = List :: from_vec ( [ 0 , 1 , 2 ] ) ;
223
+ let mut iter = list. iter ( ) ;
224
+ assert_eq ! ( & 0 , iter. next( ) . unwrap( ) ) ;
225
+ assert_eq ! ( & 1 , iter. next( ) . unwrap( ) ) ;
226
+ assert_eq ! ( & 2 , iter. next( ) . unwrap( ) ) ;
227
+ assert_eq ! ( None , iter. next( ) ) ;
228
+ }
229
+
184
230
#[ test]
185
231
fn test_is_empty ( ) {
186
232
let empty : @list:: List < int > = @List :: from_vec ( [ ] ) ;
0 commit comments