简体   繁体   English

Rust Book 中的 Rust 示例:for 循环范围

[英]Rust example in Rust Book: for loop over a range

In the Rust Book there is an interesting example about an audio encoder: Comparing Performance: Loops vs. Iterators在 Rust Book 中有一个关于音频编码器的有趣示例: Comparing Performance: Loops vs. Iterators

let buffer: &mut [i32];
let coefficients: [i64; 12];
let qlp_shift: i16;

for i in 12..buffer.len() {
    let prediction = coefficients.iter()
        .zip(&buffer[i - 12..i])
        .map(|(&c, &s)| c * s as i64)
        .sum::<i64>() >> qlp_shift;
    let delta = buffer[i];
    buffer[i] = prediction as i32 + delta;
}
  1. I cant get what is iterating this for loop.我无法得到迭代这个 for 循环的内容。 In my mind, 12..buffer.len() would iterate from the 13th byte of the buffer to the end of the buffer.在我看来, 12..buffer.len()会从缓冲区的第 13 个字节迭代到缓冲区的末尾。 Which doesn't makes much sense.这没有多大意义。

  2. Also, when zipping, it is pairing the current item in coefficients — coefficients.iter() — and pairing with buffer[i - 12..i] , which again makes no sense, as I don't know how can you take the index i and substranct a range like 12..i .此外,在压缩时,它会将系数中的当前项配对buffer[i - 12..i] coefficients.iter() ——并与buffer[i - 12..i]配对,这又没有意义,因为我不知道你怎么能接受索引i并减去一个范围,如12..i

Any help will be welcome!欢迎任何帮助!

The loop starts at 12 , thereby skipping the first 12 elements in the buffer:循环从12开始,从而跳过缓冲区中的前 12 个元素:

for i in 12..buffer.len() {

As pointed out in the comments, buffer[i - 12..i] is actually interpreted by the Rust parser as buffer[(i - 12)..i] .正如评论中指出的, buffer[i - 12..i]实际上被 Rust 解析器解释为buffer[(i - 12)..i] So, later in the algorithm it refers to the preceding 12 elements:因此,在算法的后面,它引用了前面的 12 个元素:

.zip(&buffer[i - 12..i])

This is creating a sliding window of 12 elements, starting 12 elements before the current index, and then zipping them with the fixed array of 12 coefficients.这是创建一个 12 个元素的滑动窗口,从当前索引之前的 12 个元素开始,然后用 12 个系数的固定数组压缩它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM