arrays - 使用切片和使用对数组的引用作为参数有什么区别?

标签 arrays generics rust slice

取切片有什么区别:

fn relu(xs: &mut [f64]) {
    xs.iter_mut().for_each(|x| *x = x.max(0.0));
}

并引用一个数组

fn relu<const L: usize>(xs: &mut [f64; L]) {
    xs.iter_mut().for_each(|x| *x = x.max(0.0));
}

作为参数?

是否有它的用途,或者一个比另一个更好?

最佳答案

嗯,一个slice更通用,因为可以使用的类型更多:

fn relu(xs: &mut [f64]) {
    xs.iter_mut().for_each(|x| *x = x.max(0.0));
}

您可以通过 &mut Vec&mut []&mut [_; 调用 relu N](几乎所有你可以从中制作切片的东西,记住切片只是一些连续序列的 View ),因为这些类型可以用作切片。

同时:

fn relu<const L: usize>(xs: &mut [f64; L]) {
    xs.iter_mut().for_each(|x| *x = x.max(0.0));
}

只能在 [f64; L], and 为每个使用的 L 生成一个新函数,在这种情况下几乎是资源的损失 .

正如@Masklinn 评论的那样:

OTOH a reference to an array means the iteration size is definitely known at compile-time, which can allow optimisations which the slice version may not be able to work out. So sometimes using an array reference can make sense as an optimisation assistance (in this case relu would probably be a major candidate for inlining so the important bit would really be what the type is in the caller).

关于arrays - 使用切片和使用对数组的引用作为参数有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71586633/

相关文章:

c# 泛型列表

Java通用instanceof不使用继承

javascript undefined variable /数组

arrays - 在线性时间内使用基于比较的排序对整数进行排序

java - 为什么在 T 是类型参数而 t 是变量的情况下不允许使用 "t instanceof T"?

rust - 将 unwrap_or 与泛型一起使用

rust - 如何返回结构体或比基元更复杂的东西?

rust - 如何使用 clokwerk 在调度程序上运行函数?

java - 我不知道如何为冒泡排序java定义变量

arrays - 将整数数组传递给ElasticSearch模板