mirror of
https://github.com/gnu4cn/rust-lang-zh_CN.git
synced 2026-08-19 12:43:28 +08:00
Updated src/generic_types_traits_and_lifetimes/generics.md'.
This commit is contained in:
@@ -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);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user