mirror of
https://github.com/sunface/rust-by-practice.git
synced 2025-06-23 12:39:42 +00:00
add generics.md
This commit is contained in:
@ -85,4 +85,50 @@ fn main() {
|
||||
let y = Val{ val: "hello".to_string()};
|
||||
println!("{}, {}", x.value(), y.value());
|
||||
}
|
||||
```
|
||||
```
|
||||
|
||||
6.
|
||||
```rust
|
||||
struct Point<T, U> {
|
||||
x: T,
|
||||
y: U,
|
||||
}
|
||||
|
||||
impl<T, U> Point<T, U> {
|
||||
fn mixup<V, W>(self, other: Point<V, W>) -> Point<T, W> {
|
||||
Point {
|
||||
x: self.x,
|
||||
y: other.y,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let p1 = Point { x: 5, y: 10 };
|
||||
let p2 = Point { x: "Hello", y: '中'};
|
||||
|
||||
let p3 = p1.mixup(p2);
|
||||
|
||||
assert_eq!(p3.x, 5);
|
||||
assert_eq!(p3.y, '中');
|
||||
}
|
||||
```
|
||||
|
||||
7.
|
||||
```rust
|
||||
struct Point<T> {
|
||||
x: T,
|
||||
y: T,
|
||||
}
|
||||
|
||||
impl Point<f32> {
|
||||
fn distance_from_origin(&self) -> f32 {
|
||||
(self.x.powi(2) + self.y.powi(2)).sqrt()
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let p = Point{x: 5.0_f32, y: 10.0_f32};
|
||||
println!("{}",p.distance_from_origin())
|
||||
}
|
||||
```
|
||||
|
Reference in New Issue
Block a user