+4
-2
.rustlings-state.txt
+4
-2
.rustlings-state.txt
+1
-1
exercises/14_generics/generics1.rs
+1
-1
exercises/14_generics/generics1.rs
···
6
6
// TODO: Fix the compiler error by annotating the type of the vector
7
7
// `Vec<T>`. Choose `T` as some integer type that can be created from
8
8
// `u8` and `i8`.
9
-
let mut numbers = Vec::new();
9
+
let mut numbers: Vec<i16> = Vec::new();
10
10
11
11
// Don't change the lines below.
12
12
let n1: u8 = 42;
+4
-4
exercises/14_generics/generics2.rs
+4
-4
exercises/14_generics/generics2.rs
···
1
1
// This powerful wrapper provides the ability to store a positive integer value.
2
2
// TODO: Rewrite it using a generic so that it supports wrapping ANY type.
3
-
struct Wrapper {
4
-
value: u32,
3
+
struct Wrapper<T> {
4
+
value: T,
5
5
}
6
6
7
7
// TODO: Adapt the struct's implementation to be generic over the wrapped value.
8
-
impl Wrapper {
9
-
fn new(value: u32) -> Self {
8
+
impl<T> Wrapper<T> {
9
+
fn new(value: T) -> Self {
10
10
Wrapper { value }
11
11
}
12
12
}
+15
-2
solutions/14_generics/generics1.rs
+15
-2
solutions/14_generics/generics1.rs
···
1
+
// `Vec<T>` is generic over the type `T`. In most cases, the compiler is able to
2
+
// infer `T`, for example after pushing a value with a concrete type to the vector.
3
+
// But in this exercise, the compiler needs some help through a type annotation.
4
+
1
5
fn main() {
2
-
// DON'T EDIT THIS SOLUTION FILE!
3
-
// It will be automatically filled after you finish the exercise.
6
+
// `u8` and `i8` can both be converted to `i16`.
7
+
let mut numbers: Vec<i16> = Vec::new();
8
+
// ^^^^^^^^^^ added
9
+
10
+
// Don't change the lines below.
11
+
let n1: u8 = 42;
12
+
numbers.push(n1.into());
13
+
let n2: i8 = -1;
14
+
numbers.push(n2.into());
15
+
16
+
println!("{numbers:?}");
4
17
}
+26
-2
solutions/14_generics/generics2.rs
+26
-2
solutions/14_generics/generics2.rs
···
1
+
struct Wrapper<T> {
2
+
value: T,
3
+
}
4
+
5
+
impl<T> Wrapper<T> {
6
+
fn new(value: T) -> Self {
7
+
Wrapper { value }
8
+
}
9
+
}
10
+
1
11
fn main() {
2
-
// DON'T EDIT THIS SOLUTION FILE!
3
-
// It will be automatically filled after you finish the exercise.
12
+
// You can optionally experiment here.
13
+
}
14
+
15
+
#[cfg(test)]
16
+
mod tests {
17
+
use super::*;
18
+
19
+
#[test]
20
+
fn store_u32_in_wrapper() {
21
+
assert_eq!(Wrapper::new(42).value, 42);
22
+
}
23
+
24
+
#[test]
25
+
fn store_str_in_wrapper() {
26
+
assert_eq!(Wrapper::new("Foo").value, "Foo");
27
+
}
4
28
}