Updated src/generic_types_traits_and_lifetimes/generics.md'.

This commit is contained in:
Hector PENG
2026-03-22 14:55:09 +08:00
parent ba0e76f3dc
commit 544f0ce80d
2 changed files with 35 additions and 38 deletions

View File

@@ -1,22 +1,23 @@
struct Point<T> {
x: T,
y: T,
#[derive(Debug)]
struct Point<X1, Y1> {
x: X1,
y: Y1,
}
impl<T> Point<T> {
fn x(&self) -> &T {
&self.x
}
}
impl Point<f32, f32> {
fn distance_from_origin(&self) -> f32 {
(self.x.powi(2) + self.y.powi(2)).sqrt()
impl<X1, Y1> Point<X1, Y1> {
fn mixup<X2, Y2>(self, other: Point<X2, Y2>) -> Point<X1, Y2> {
Point {
x: self.x,
y: other.y,
}
}
}
fn main() {
let p = Point { x: 5, y: 10 };
let p1 = Point { x: 5, y: 10.4 };
let p2 = Point { x: "Hello", y: 'c' };
println!("p.x = {}", p.x());
let p3 = p1.mixup(p2);
println! ("p3.x = {}, p3.y = {}", p3.x, p3.y);
}