generics-traits/generics #194
Replies: 6 comments 4 replies
|
头两题都是 1 |
3 replies
|
第7题,我改成了 |
1 reply
|
// 实现下面的泛型函数 sum fn main() { |
0 replies
|
第6题:编译通过后,可以试试将 main函数中这个表达式 let p3 = p1.mixup(p2); 改为 let p3 = p2.mixup(p1); 可以再调试看看能不能编译过。感觉这样对泛型的理解又会深一点。 |
0 replies
#[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);
} |
0 replies
|
第七题只改方法,不改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())
}这样数字类型都能用。 |
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
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
All reactions