add generic.md

This commit is contained in:
sunface
2022-03-03 17:13:21 +08:00
parent 7ea642691e
commit a8f251fd2a
6 changed files with 202 additions and 2 deletions

View File

@ -1 +1,98 @@
# Generics
### Functions
1. 🌟🌟🌟
```rust,editable
// fill in the blanks to make it work
struct A; // Concrete type `A`.
struct S(A); // Concrete type `S`.
struct SGen<T>(T); // Generic type `SGen`.
fn reg_fn(_s: S) {}
fn gen_spec_t(_s: SGen<A>) {}
fn gen_spec_i32(_s: SGen<i32>) {}
fn generic<T>(_s: SGen<T>) {}
fn main() {
// Using the non-generic functions
reg_fn(__); // Concrete type.
gen_spec_t(__); // Implicitly specified type parameter `A`.
gen_spec_i32(__); // Implicitly specified type parameter `i32`.
// Explicitly specified type parameter `char` to `generic()`.
generic::<char>(__);
// Implicitly specified type parameter `char` to `generic()`.
generic(__);
}
```
2. 🌟🌟 A function call with explicitly specified type parameters looks like: `fun::<A, B, ...>()`.
```rust,editable
// implement a generic function
fn sum
fn main() {
assert_eq!(5, sum(2i8, 3i8));
assert_eq!(50, sum(20, 30));
assert_eq!(2.46, sum(1.23, 1.23));
}
```
### Struct and `impl`
3. 🌟
```rust,editable
// implement struct Point to make it work
fn main() {
let integer = Point { x: 5, y: 10 };
let float = Point { x: 1.0, y: 4.0 };
}
```
4. 🌟🌟
```rust,editable
// modify this struct to make the code work
struct Point<T> {
x: T,
y: T,
}
fn main() {
// DON'T modify here
let p = Point{x: 5, y : "hello".to_string()};
}
```
5. 🌟🌟
```rust,editable
// add generic for Val to make the code work, DON'T modify the code in `main`
struct Val {
val: f64,
}
impl Val {
fn value(&self) -> &f64 {
&self.val
}
}
fn main() {
let x = Val{ val: 3.0 };
let y = Val{ val: "hello".to_string()};
println!("{}, {}", x.value(), y.value());
}
```
> You can find the solutions [here](https://github.com/sunface/rust-by-practice)(under the solutions path), but only use it when you need it