泛型类型'T'上没有字段'foo'

时间:2018-05-15 15:36:30

标签: generics rust

我尝试在Rust中实现一个构建器模式作为练习。然后,我想用泛型来实现struct Director来处理具体的Builder并计算两点之间的距离。

请对不安全的代码视而不见:

struct VecLengthDirector<T> {
    builder: T,
}

impl<T> VecLengthDirector<T> {
    fn construct(&self) -> f64 {
        let s = self.builder.start.unwrap();
        let e = self.builder.end.unwrap();

        let mut sum: i32 = 0;
        for i in 0..s.len() {
            sum += (s[i] - e[i]).pow(2);
        }

        (sum as f64).sqrt()
    }
}

trait AbstractVecLengthBuider<T> {
    fn addStartPoint(&mut self, point: T);
    fn addEndPoint(&mut self, point: T);
}

struct TwoDimVecLengthBuilder {
    start: Option<[i32; 2]>,
    end: Option<[i32; 2]>,
}

impl AbstractVecLengthBuider<[i32; 2]> for TwoDimVecLengthBuilder {
    fn addStartPoint(&mut self, point: [i32; 2]) {
        self.start = Some(point);
    }
    fn addEndPoint(&mut self, point: [i32; 2]) {
        self.end = Some(point);
    }
}

pub fn test() {
    let mut veclen1 = VecLengthDirector {
        builder: TwoDimVecLengthBuilder {
            start: None,
            end: None,
        },
    };
    veclen1.builder.addStartPoint([0, 0]);
    veclen1.builder.addEndPoint([1, 1]);
    println!(
        "Distance between [0, 0] and [1, 1] is: {}",
        veclen1.construct()
    );
}

运行此代码后,会报告以下错误:

error[E0609]: no field `start` on type `T`
 --> src/main.rs:7:30
  |
7 |         let s = self.builder.start.unwrap();
  |                              ^^^^^

error[E0609]: no field `end` on type `T`
 --> src/main.rs:8:30
  |
8 |         let e = self.builder.end.unwrap();
  |                              ^^^

我研究了错误代码并阅读了Rust的文档,但我无法理解发生了什么以及出了什么问题。

0 个答案:

没有答案