[英]How do I make a Rust function generic over array size?
我的代碼通常與長度為 303 的 arrays 一起使用,我很高興將這個數字硬編碼到我的代碼中。 但出於測試目的,我想展示一些功能在較小的 arrays 上的行為。 如何實現以下逐點 function 的等效項? 或者這是不可能的,我將只使用切片並在運行時明確檢查每個切片的大小,而不是依賴編譯器不讓任何東西溜走?
pub fn recover<N>(
mut patch_resources: &[KCal; N],
patch_max_resources: &[KCal; N],
resource_recovery: f32,
accessible_resources: f32)
where
N: usize
{
for i in N {
if patch_resources[i] < patch_max_resources[i] {
let inaccessible = patch_max_resources[i] * (1. - accessible_resources) / accessible_resources;
let underlying_resources = patch_resources[i] + inaccessible;
patch_resources[i] += underlying_resources
* resource_recovery
* (1. - underlying_resources * accessible_resources/ patch_max_resources[i]);
}
assert!(patch_resources[i].is_normal());
}
}
我認為您需要通用數組板條箱。
我認為你的代碼會是這樣的
pub fn recover<N>(
mut patch_resources: &GenericArray<KCal, N>,
patch_max_resources: &GenericArray<KCal, N>,
resource_recovery: f32,
accessible_resources: f32)
where
N: ArrayLength<usize>
{
for i in N {
if patch_resources[i] < patch_max_resources[i] {
let inaccessible = patch_max_resources[i] * (1. - accessible_resources) / accessible_resources;
let underlying_resources = patch_resources[i] + inaccessible;
patch_resources[i] += underlying_resources
* resource_recovery
* (1. - underlying_resources * accessible_resources/ patch_max_resources[i]);
}
assert!(patch_resources[i].is_normal());
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.