File tree Expand file tree Collapse file tree 1 file changed +24
-5
lines changed
content/lessons/05_types_reasoning Expand file tree Collapse file tree 1 file changed +24
-5
lines changed Original file line number Diff line number Diff line change 51
51
}
52
52
}
53
53
54
- // Here information about the concrete underlying type is erased
55
- // We can only either format or clone the result
56
- fn cloning_machine ( item : & ( impl Clone + Debug ) ) -> impl Clone + Debug {
54
+ // Here information about the concrete underlying type is preserved.
55
+ fn cloning_machine < T : Clone + Debug > ( item : & T ) -> T {
56
+ item. clone ( )
57
+ }
58
+
59
+ // Here information about the concrete underlying type is erased.
60
+ // We can only either format or clone the result.
61
+ fn erasing_cloning_machine1 ( item : & ( impl Clone + Debug ) ) -> impl Clone + Debug {
62
+ item. clone ( )
63
+ }
64
+
65
+ // Ditto.
66
+ fn erasing_cloning_machine2 < T : Clone + Debug > ( item : & T ) -> impl Clone + Debug {
57
67
item. clone ( )
58
68
}
59
69
@@ -64,7 +74,16 @@ fn main() {
64
74
let _p2 = Tuple2 :: new ( 1 , 2.5 ) ;
65
75
66
76
let arr = [ 1 , 2 , 3 ] ;
77
+
67
78
let arr2 = cloning_machine ( & arr) ;
68
- // arr2[0]; // won't compile: cannot index into a value of type `impl std::clone::Clone + std::fmt::Debug`
69
- println ! ( "{:?}" , arr2)
79
+ let _x = arr2[ 0 ] ; // This compiles, because `cloning_machine` preserves the type.
80
+ println ! ( "{:?}" , arr2) ;
81
+
82
+ let arr3 = erasing_cloning_machine1 ( & arr) ;
83
+ // arr3[0]; // won't compile: cannot index into a value of type `impl std::clone::Clone + std::fmt::Debug`
84
+ println ! ( "{:?}" , arr3) ;
85
+
86
+ let arr4 = erasing_cloning_machine2 ( & arr) ;
87
+ // arr4[0]; // won't compile: cannot index into a value of type `impl std::clone::Clone + std::fmt::Debug`
88
+ println ! ( "{:?}" , arr4) ;
70
89
}
You can’t perform that action at this time.
0 commit comments