我试图访问一个结构体的不同字段,但我得到以下错误:
error[E0609]: no field `x` on type `Point`
--> src/lib.rs:9:31
|
8 | fn distance<Point>(point1: &Point, point2: &Point) -> f64 {
| ----- type parameter 'Point' declared here
9 | let diffX = (*point1).x - (*point2).x;
| ^
for x, y和z:
pub struct Point {
pub x: f64,
pub y: f64,
pub z: f64,
}
impl Point {
fn distance<Point>(point1: &Point, point2: &Point) -> f64 {
let diffX = (*point1).x - (*point2).x;
let diffY = (*point1).y - (*point2).y;
let diffZ = (*point1).z - (*point2).z;
(diffX * diffX + diffY * diffY + diffZ * diffZ).sqrt()
}
}
我在这里做错了什么?
error[E0609]: no field `x` on type `Point`
--> src/lib.rs:9:31
|
8 | fn distance<Point>(point1: &Point, point2: &Point) -> f64 {
| ----- type parameter 'Point' declared here
9 | let diffX = (*point1).x - (*point2).x;
| ^
错误信息显示Point
是第8行声明的type parameter
,这掩盖了前面声明的原始Point
类型。
所以解决方案是将这个泛型类型更改为另一个名称,或者只是删除它,因为我在函数体中没有发现它的任何用法。
pub struct Point {
pub x: f64,
pub y: f64,
pub z: f64,
}
impl Point {
fn distance(point1: &Point, point2: &Point) -> f64 {
let diffX = (*point1).x - (*point2).x;
let diffY = (*point1).y - (*point2).y;
let diffZ = (*point1).z - (*point2).z;
(diffX * diffX + diffY * diffY + diffZ * diffZ).sqrt()
}
}