Selaa lähdekoodia

implement first and last for list_with_ref.

Lucas Stadler 11 vuotta sitten
vanhempi
commit
6aadb6f206
1 muutettua tiedostoa jossa 21 lisäystä ja 0 poistoa
  1. 21 0
      rust/pointers.rs

+ 21 - 0
rust/pointers.rs

@ -102,6 +102,22 @@ mod list_with_ref {
102 102
        }
103 103
    }
104 104
105
    pub fn first<'a, A>(xs: &'a List<A>) -> Option<&'a A> {
106
        match *xs {
107
            Nil => None,
108
            // note the `ref x` here, the default would again be moving the value
109
            Cons(ref x, _) => Some(x)
110
        }
111
    }
112
113
    pub fn last<'a, A>(xs: &'a List<A>) -> Option<&'a A> {
114
        match *xs {
115
            Nil => None,
116
            Cons(ref x, &Nil) => Some(x),
117
            Cons(_, xs) => last(xs)
118
        }
119
    }
120
105 121
    pub fn run() {
106 122
        println!("\nlist_with_ref:");
107 123
@ -111,6 +127,11 @@ mod list_with_ref {
111 127
112 128
        println!("l = {:?}", l);
113 129
        println!("cons(1, l) = {:?}", cons(1, l));
130
131
        let l2: &List<int> = &cons(2, l);
132
        println!("l2 = {:?}", l2);
133
        println!("first(l2) = {:?}", first(l2));
134
        println!("last(l2)  = {:?}", last(l2));
114 135
    }
115 136
}
116 137