如何重用范围来获取数组的部分?

时间:2018-02-07 17:39:13

标签: rust

我正在处理不同大小的块(3,4,5等)(link to the playground):

error[E0277]: the trait bound `&std::ops::Range<{integer}>: std::slice::SliceIndex<[u8]>` is not satisfied
  --> src/main.rs:20:29
   |
20 |         let group_sum: u8 = arr[&range].iter().sum();
   |                             ^^^^^^^^^^^ slice indices are of type `usize` or ranges of `usize`
   |
   = help: the trait `std::slice::SliceIndex<[u8]>` is not implemented for `&std::ops::Range<{integer}>`
   = note: required because of the requirements on the impl of `std::ops::Index<&std::ops::Range<{integer}>>` for `[u8]`

error[E0277]: the trait bound `&std::ops::Range<{integer}>: std::slice::SliceIndex<[u8]>` is not satisfied
  --> src/main.rs:21:26
   |
21 |         for (idx, el) in arr[&range].iter().enumerate() {
   |                          ^^^^^^^^^^^ slice indices are of type `usize` or ranges of `usize`
   |
   = help: the trait `std::slice::SliceIndex<[u8]>` is not implemented for `&std::ops::Range<{integer}>`
   = note: required because of the requirements on the impl of `std::ops::Index<&std::ops::Range<{integer}>>` for `[u8]`

error[E0277]: the trait bound `&std::ops::Range<{integer}>: std::slice::SliceIndex<[u8]>` is not satisfied
  --> src/main.rs:22:13
   |
22 |             results[&range][idx] = el * group_sum * corrections[&range][idx];
   |             ^^^^^^^^^^^^^^^ slice indices are of type `usize` or ranges of `usize`
   |
   = help: the trait `std::slice::SliceIndex<[u8]>` is not implemented for `&std::ops::Range<{integer}>`
   = note: required because of the requirements on the impl of `std::ops::Index<&std::ops::Range<{integer}>>` for `[u8]`

error[E0277]: the trait bound `&std::ops::Range<{integer}>: std::slice::SliceIndex<[u8]>` is not satisfied
  --> src/main.rs:22:53
   |
22 |             results[&range][idx] = el * group_sum * corrections[&range][idx];
   |                                                     ^^^^^^^^^^^^^^^^^^^ slice indices are of type `usize` or ranges of `usize`
   |
   = help: the trait `std::slice::SliceIndex<[u8]>` is not implemented for `&std::ops::Range<{integer}>`
   = note: required because of the requirements on the impl of `std::ops::Index<&std::ops::Range<{integer}>>` for `[u8]`

返回错误:

range

使用&range代替use of moved value会产生range.clone()错误。是否可以在不使用SpreadsheetApp.addEditor('theEmailThatIWantToEnabled@email.com'); 全部工作的情况下工作?

1 个答案:

答案 0 :(得分:4)

不,目前无法实现。传递给切片的index方法(a.k.a。[])的有效值是实现SliceIndex特征的那些类型。 &Range不在该列表中,但我不知道是否有任何技术原因阻止它出现这种情况。

除了这种情况下克隆的表现......

当您致电foo[1..2]时,您将创建的Range<usize>的所有权转移到Index::index,其中包含两个usize值。如果我们 能够传递&Range,我们只会传递一个usize值,但我们必须执行解除引用然后复制至少有一个内部usize。我的(未经检验的)假设是它比克隆慢。

另见