File tree 2 files changed +54
-0
lines changed
2 files changed +54
-0
lines changed Original file line number Diff line number Diff line change @@ -26,6 +26,7 @@ in a controlled repository now.
26
26
* ` addy.rs ` : trait def/impl example
27
27
* ` bno-salad.rs ` : trait salad example from Blandy and Orendorff
28
28
* ` matmul.rs ` : example of overloading multiplication for matrices
29
+ * ` stacks.rs ` : example defining a stack trait
29
30
* ` phantom.rs ` : phantom type example
30
31
* ` deref.rs ` : deref trait example
31
32
* ` from.rs ` : from / try_from trait example
Original file line number Diff line number Diff line change
1
+ use std:: collections:: LinkedList ;
2
+
3
+ pub trait Stack < T > {
4
+ fn spush ( & mut self , v : T ) ;
5
+ fn spop ( & mut self ) -> Option < T > ;
6
+ }
7
+
8
+ impl < ' a , T : ?Sized > Stack < & ' a T > for Vec < & ' a T > {
9
+ fn spush ( & mut self , v : & ' a T ) {
10
+ self . push ( v) ;
11
+ }
12
+
13
+ fn spop ( & mut self ) -> Option < & ' a T > {
14
+ self . pop ( )
15
+ }
16
+ }
17
+
18
+ impl < ' a , T : ?Sized > Stack < & ' a T > for LinkedList < & ' a T > {
19
+ fn spush ( & mut self , v : & ' a T ) {
20
+ self . push_front ( v) ;
21
+ }
22
+
23
+ fn spop ( & mut self ) -> Option < & ' a T > {
24
+ self . pop_front ( )
25
+ }
26
+ }
27
+
28
+ pub fn dup < ' a , ' b : ' a , S , T > ( stack : & mut S )
29
+ where S : Stack < & ' b T > + ' a , T : ' b + ?Sized
30
+ {
31
+ let v = stack. spop ( ) . unwrap ( ) ;
32
+ stack. spush ( v) ;
33
+ stack. spush ( v) ;
34
+ }
35
+
36
+ #[ cfg( test) ]
37
+ mod test {
38
+ use crate :: * ;
39
+
40
+ fn test < S > ( mut s : S ) where S : Stack < & ' static str > {
41
+ s. spush ( "hello" ) ;
42
+ dup ( & mut s) ;
43
+ assert_eq ! ( s. spop( ) . unwrap( ) , "hello" ) ;
44
+ assert_eq ! ( s. spop( ) . unwrap( ) , "hello" ) ;
45
+ assert_eq ! ( s. spop( ) , None ) ;
46
+ }
47
+
48
+ #[ test]
49
+ fn test_impls ( ) {
50
+ test ( Vec :: new ( ) ) ;
51
+ test ( LinkedList :: new ( ) ) ;
52
+ }
53
+ }
You can’t perform that action at this time.
0 commit comments