rustkdtree

How do I write the type of a KdTree member in a struct?


I'm trying to use the kdtree crate to explore function approximation from sampled points.

I have a struct which is supposed to have a kdtree member. The type of the KdTree is generic and the third parameter gives me a headache:

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

This is my attempt:

use kdtree;

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

The error I am getting is

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`

How do I write it so it compiles? My Approximator will also have some runtime dimension depending on the n-arity of the function I try to approximate.


Solution

  • From looking at the code I came up with the following interpretation on the types required to define kdtree:

    // The definition is of the form: KdTree<A, T, U> it has 3 generic types:
    // A = the type used for the partion space - it has to be a float type
    // T = the attribute type - in this case its an integer usize
    // U = the type used for the points in this case: [f32, f32, f32]
    //
    // U must be of the same type as type A as it needs to satisfy the 
    // constrain AsRef<[A]> and it must match the number of dimensions 
    // when calling new()
    

    There are some code examples in this article, that I wrote: KDTrees in Rust for Searching Spatial Data