2017-04-14 42 views
6

最近,我想寫一型保持參數的3D投影:爲什麼不ops :: Range <T>實現複製,即使T是複製?

use std::ops::Range; 

#[derive(Clone, Copy)] 
struct CamProj { 
    /// Near and far plane 
    proj_range: Range<f32>, 
    /// Field of view 
    fov: cgmath::Rad<f32>,  // `Rad` derives `Copy` 
    /// Width divided by height 
    aspect_ratio: f32,  
} 

不過,我得到這個錯誤:

error[E0204]: the trait `Copy` may not be implemented for this type 
--> <anon>:3:21 
    | 
3 |  #[derive(Clone, Copy)] 
    |      ^^^^ 
... 
6 |   proj_range: Range<f32>, 
    |   ---------------------- this field does not implement `Copy` 

因此很明顯,Range<T>從未實現Copy,即使TCopy,就像f32是。 這是爲什麼?我以爲Range<T>只是一對T?所以它肯定可以實現Copy

+2

我敢肯定,我以前見過這個問題...但當然不能再次找到它。我找到的最接近的潛在副本是http://stackoverflow.com/questions/31045637/re-using-a-range-for-iteration。我似乎記得它沒有實現,因爲有些情況下可能會讓人困惑:https://github.com/rust-lang/rust/issues/18045 –

回答

7

因爲Range<T>經常用作迭代器,並且迭代器是Copywas discovered to be a footgunOne specific example曾與思考,迭代器被推進了,但實際上它是一個副本,這是先進的辦:

for x in it { // a *copy* of the iterator is used here 
    // .. 
} 

match it.next() { // the original iterator is used here 
    // .. 
} 

Another example

fn main() { 
    let stream = "Hello, world!".chars().cycle(); 
    for _ in 0..10 { 
     let chunk: String = stream.take(3).collect(); 
     println!("{}", chunk); 
    } 
} 

,另一個提示一個問題:Using the same iterator multiple times in Rust

據認爲,通過clone明確複製迭代器有助於防止這些情況


特別重新添加CopyRangewas proposed and rejected。一個潛在的解決方法建議:

Range fields are public, you can repack them into a copyable tuple (or equivalent) at the constructor/function boundary

參見:

相關問題