如何在结构中写入KdTree成员的类型?

时间:2019-05-08 22:17:25

标签: rust kdtree

我正在尝试使用kdtree crate来从采样点探索函数逼近。

我有一个应该具有kdtree成员的结构。 KdTree的类型是通用的,第三个参数让我头疼:

pub struct KdTree<A, T, U: AsRef<[A]>> { /* fields omitted */ }

这是我的尝试:

use kdtree;

pub struct Approximator {
    tree: kdtree::KdTree<f32, f32, AsRef<[f32]>>,
}

我得到的错误是

error[E0277]: the size for values of type `(dyn std::convert::AsRef<[f32]> + 'static)` cannot be known at compilation time
 --> src/main.rs:4:5
  |
4 |     tree: kdtree::KdTree<f32, f32, AsRef<[f32]>>,
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time
  |
  = help: the trait `std::marker::Sized` is not implemented for `(dyn std::convert::AsRef<[f32]> + 'static)`
  = note: to learn more, visit <https://doc.rust-lang.org/book/ch19-04-advanced-types.html#dynamically-sized-types-and-the-sized-trait>
  = note: required by `kdtree::kdtree::KdTree`

我如何编写它以便进行编译?我的Approximator也将有一些运行时dimension,具体取决于我尝试逼近的函数的n个值。

1 个答案:

答案 0 :(得分:0)

我想我已经知道了。当您从文档中粘贴示例代码时

let a: ([f64; 2], usize) = ([0f64, 0f64], 0);
let b: ([f64; 2], usize) = ([1f64, 1f64], 1);
let c: ([f64; 2], usize) = ([2f64, 2f64], 2);
let d: ([f64; 2], usize) = ([3f64, 3f64], 3);

let dimensions = 2;
let mut kdtree = KdTree::new(dimensions);

kdtree.add(&a.0, a.1).unwrap();
kdtree.add(&b.0, b.1).unwrap();
kdtree.add(&c.0, c.1).unwrap();
kdtree.add(&d.0, d.1).unwrap();

您发现kdtree的类型为kdtree::kdtree::KdTree<f64, usize, &[f64; 2]>