Skip to content

Commit 364f920

Browse files
committed
05: extend generics example: impl vs T
1 parent 0697c66 commit 364f920

File tree

1 file changed

+24
-5
lines changed

1 file changed

+24
-5
lines changed

content/lessons/05_types_reasoning/generics.rs

Lines changed: 24 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -51,9 +51,19 @@ where
5151
}
5252
}
5353

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 {
5767
item.clone()
5868
}
5969

@@ -64,7 +74,16 @@ fn main() {
6474
let _p2 = Tuple2::new(1, 2.5);
6575

6676
let arr = [1, 2, 3];
77+
6778
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);
7089
}

0 commit comments

Comments
 (0)