generics-traits/generics #194
Replies: 6 comments 4 replies
-
第7题,我改成了 |
Beta Was this translation helpful? Give feedback.
-
// 实现下面的泛型函数 sum fn main() { |
Beta Was this translation helpful? Give feedback.
-
第6题:编译通过后,可以试试将 main函数中这个表达式 let p3 = p1.mixup(p2); 改为 let p3 = p2.mixup(p1); 可以再调试看看能不能编译过。感觉这样对泛型的理解又会深一点。 |
Beta Was this translation helpful? Give feedback.
-
#[derive(Debug)]
struct Point<T: Copy, U: Copy> {
x: T,
y: U,
}
impl<T: Copy, U: Copy> Point<T, U> {
// 实现 mixup,不要修改其它代码!
fn mixup<V: Copy, W: Copy>(&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);
let p4 = p2.mixup(&p1);
assert_eq!(p3.x, 5);
assert_eq!(p3.y, '中');
println!("{:?}", p1);
println!("{:?}", p2);
println!("{:?}", p3);
println!("{:?}", p4);
} |
Beta Was this translation helpful? Give feedback.
-
第七题只改方法,不改main调用: // 修复错误,让代码工作
struct Point<T> {
x: T,
y: T,
}
impl <T> Point<T> where T: Into<f64> + Copy {
fn distance_from_origin(&self) -> f64 {
(self.x.into().powi(2) + self.y.into().powi(2)).sqrt()
}
}
fn main() {
let p = Point{x: 5, y: 10};
println!("{}",p.distance_from_origin())
} 这样数字类型都能用。 |
Beta Was this translation helpful? Give feedback.
-
generics-traits/generics
Learning Rust By Practice, narrowing the gap between beginner and skilled-dev with challenging examples, exercises and projects.
https://zh.practice.rs/generics-traits/generics.html
Beta Was this translation helpful? Give feedback.
All reactions