I am trying to port C ++ code to Rust. I tried many different approaches, but not one of them compiles.
I want a generic template that can handle various types and has an adjustable total size with a static field (Set expression) Capacity :
template<class KeyType, class ValueType, int PageSize> struct BplusTreeLeaf { static const uint16_t Capacity = (PageSize-16)/(sizeof(KeyType)+sizeof(ValueType)); KeyType keys[Capacity]; ValueType values[Capacity]; };
I want to access the tank outside:
for(int i = 0; i < BplusTreeLeaf<x, y, 4096>::Capacity; i ++) { ... }
There seems to be no way in Rust to do something like this, or at least in my understanding of Rust:
static not allowed in the structure and the documentation tells me to use macros- in Rust, only types are "template", not values ββor expressions. I can't even pass the total size as an argument to define the structure
This is how much I got:
macro_rules! BplusTreeLeaf { ($KeyType:ident, $ValueType:ident, $PageSize:expr) => { static Capacity_: u16 = ($PageSize - 16) / (std::mem::size_of::<$KeyType>() + std::mem::size_of::<$ValueType>()); struct BplusTreeLeaf_ { keys: [$KeyType, ..Capacity_], values: [$ValueType, ..Capacity_], } } } BplusTreeLeaf!(u64, u64, 4096)
The compiler yields the "expected constant expr for the length of the vector", which is incorrect because I did not use "mut" for Capacity_ , so it should be a const expression. Even if it works, Capacity_ and BplusTreeLeaf_ will still be in the global scope / namespace.
Am I misunderstood something basic in Rust design or is it just not possible? If this is not possible now, is something planned as a future function or should I stay with C ++ 11?