Generics
Functions
- 🌟🌟🌟
2. // Fill in the blanks to make it work
3. struct A; // Concrete type `A`.
4. struct S(A); // Concrete type `S`.
5. struct SGen<T>(T); // Generic type `SGen`.
7. fn reg_fn(_s: S) {}
9. fn gen_spec_t(_s: SGen<A>) {}
11. fn gen_spec_i32(_s: SGen<i32>) {}
13. fn generic<T>(_s: SGen<T>) {}
15. fn main() {
16. // Using the non-generic functions
17. reg_fn(__); // Concrete type.
18. gen_spec_t(__); // Implicitly specified type parameter `A`.
19. gen_spec_i32(__); // Implicitly specified type parameter `i32`.
21. // Explicitly specified type parameter `char` to `generic()`.
22. generic::<char>(__);
24. // Implicitly specified type parameter `char` to `generic()`.
25. generic(__);
27. println!("Success!");
28. }
- 🌟🌟 A function call with explicitly specified type parameters looks like:
fun::<A, B, ...>().
2. // Implement the generic function below.
3. fn sum
5. fn main() {
6. assert_eq!(5, sum(2i8, 3i8));
7. assert_eq!(50, sum(20, 30));
8. assert_eq!(2.46, sum(1.23, 1.23));
10. println!("Success!");
11. }
Struct and impl
- 🌟
2. // Implement struct Point to make it work.
4. fn main() {
5. let integer = Point { x: 5, y: 10 };
6. let float = Point { x: 1.0, y: 4.0 };
8. println!("Success!");
9. }
- 🌟🌟
2. // Modify this struct to make the code work
3. struct Point<T> {
4. x: T,
5. y: T,
6. }
8. fn main() {
9. // DON'T modify this code.
10. let p = Point{x: 5, y : "hello".to_string()};
12. println!("Success!");
13. }
- 🌟🌟
2. // Add generic for Val to make the code work, DON'T modify the code in `main`.
3. struct Val {
4. val: f64,
5. }
7. impl Val {
8. fn value(&self) -> &f64 {
9. &self.val
10. }
11. }
13. fn main() {
14. let x = Val{ val: 3.0 };
15. let y = Val{ val: "hello".to_string()};
16. println!("{}, {}", x.value(), y.value());
17. }
Method
- 🌟🌟🌟
1. struct Point<T, U> {
2. x: T,
3. y: U,
4. }
6. impl<T, U> Point<T, U> {
7. // Implement mixup to make it work, DON'T modify other code.
8. fn mixup
9. }
11. fn main() {
12. let p1 = Point { x: 5, y: 10 };
13. let p2 = Point { x: "Hello", y: '中'};
15. let p3 = p1.mixup(p2);
17. assert_eq!(p3.x, 5);
18. assert_eq!(p3.y, '中');
20. println!("Success!");
21. }
- 🌟🌟
2. // Fix the errors to make the code work.
3. struct Point<T> {
4. x: T,
5. y: T,
6. }
8. impl Point<f32> {
9. fn distance_from_origin(&self) -> f32 {
10. (self.x.powi(2) + self.y.powi(2)).sqrt()
11. }
12. }
14. fn main() {
15. let p = Point{x: 5, y: 10};
16. println!("{}",p.distance_from_origin());
17. }
You can find the solutions here(under the solutions path), but only use it when you need it
