mirror of
https://github.com/sunface/rust-by-practice.git
synced 2025-06-23 04:29:41 +00:00
add generic.md
This commit is contained in:
88
solutions/generics-traits/generics.md
Normal file
88
solutions/generics-traits/generics.md
Normal file
@ -0,0 +1,88 @@
|
||||
1.
|
||||
```rust
|
||||
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(S(A)); // Concrete type.
|
||||
gen_spec_t(SGen(A)); // Implicitly specified type parameter `A`.
|
||||
gen_spec_i32(SGen(6)); // Implicitly specified type parameter `i32`.
|
||||
|
||||
// Explicitly specified type parameter `char` to `generic()`.
|
||||
generic::<char>(SGen('a'));
|
||||
|
||||
// Implicitly specified type parameter `char` to `generic()`.
|
||||
generic(SGen('c'));
|
||||
}
|
||||
```
|
||||
|
||||
2.
|
||||
```rust
|
||||
fn sum<T:std::ops::Add<Output = T>>(x: T, y: T) -> T {
|
||||
x + y
|
||||
}
|
||||
|
||||
fn main() {
|
||||
assert_eq!(5, sum(2i8, 3i8));
|
||||
assert_eq!(50, sum(20, 30));
|
||||
assert_eq!(2.46, sum(1.23, 1.23));
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
3.
|
||||
```rust
|
||||
struct Point<T> {
|
||||
x: T,
|
||||
y: T,
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let integer = Point { x: 5, y: 10 };
|
||||
let float = Point { x: 1.0, y: 4.0 };
|
||||
}
|
||||
```
|
||||
|
||||
4.
|
||||
```rust
|
||||
// modify this struct to make the code work
|
||||
struct Point<T, U> {
|
||||
x: T,
|
||||
y: U,
|
||||
}
|
||||
|
||||
fn main() {
|
||||
// DON'T modify here
|
||||
let p = Point{x: 5, y : "hello".to_string()};
|
||||
}
|
||||
```
|
||||
|
||||
5.
|
||||
```rust
|
||||
struct Val<T> {
|
||||
val: T,
|
||||
}
|
||||
|
||||
impl<T> Val<T> {
|
||||
fn value(&self) -> &T {
|
||||
&self.val
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
fn main() {
|
||||
let x = Val{ val: 3.0 };
|
||||
let y = Val{ val: "hello".to_string()};
|
||||
println!("{}, {}", x.value(), y.value());
|
||||
}
|
||||
```
|
Reference in New Issue
Block a user