Extract from my code:
use csv::Reader;
use rand::seq::index::{IndexVecIntoIter,sample};
use rand::thread_rng;
pub struct SamplingIter<I: ExactSizeIterator<Item = T>, T> {
iter: I,
indices: IndexVecIntoIter,
}
pub trait SamplingIterator: ExactSizeIterator + Sized {
fn sample(self, amount: usize) -> SamplingIter<Self, Self::Item> {
let len = self.len();
SamplingIter {iter: self, indices: sample(&mut thread_rng(), len, amount).into_iter()}
}
}
impl<I: ExactSizeIterator + Sized> SamplingIterator for I {}
impl<I: ExactSizeIterator<Item = T>, T> Iterator for SamplingIter<I, T>{
type Item = T;
fn next(&mut self) -> Option<Self::Item> {
todo!();
}
}
pub fn example() {
let mut rdr = Reader::from_path("foo.csv").unwrap();
rdr.byte_records().sample(5);
}
Cargo.toml:
[package]
name = "trait-issue"
version = "0.1.0"
edition = "2021"
[lib]
crate-type = ["cdylib"]
[dependencies]
csv = "1.2"
rand = "0.8.5"
Error message:
Checking trait-issue v0.1.0 (/Users/camdennarzt/Developer/Rust/trait-issue)
error[E0599]: the method `sample` exists for struct `ByteRecordsIter<'_, File>`, but its trait bounds were not satisfied
--> src/lib.rs:30:24
|
30 | rdr.byte_records().sample(5);
| ^^^^^^ method cannot be called on `ByteRecordsIter<'_, File>` due to unsatisfied trait bounds
|
::: /Users/camdennarzt/.cargo/registry/src/index.crates.io-6f17d22bba15001f/csv-1.2.2/src/reader.rs:2130:1
|
2130 | pub struct ByteRecordsIter<'r, R: 'r> {
| -------------------------------------
| |
| doesn't satisfy `ByteRecordsIter<'_, File>: ExactSizeIterator`
| doesn't satisfy `ByteRecordsIter<'_, File>: SamplingIterator`
|
note: the following trait bounds were not satisfied:
`&ByteRecordsIter<'_, File>: ExactSizeIterator`
`&mut ByteRecordsIter<'_, File>: ExactSizeIterator`
`ByteRecordsIter<'_, File>: ExactSizeIterator`
--> src/lib.rs:18:9
|
18 | impl<I: ExactSizeIterator + Sized> SamplingIterator for I {}
| ^^^^^^^^^^^^^^^^^ ---------------- -
| |
| unsatisfied trait bound introduced here
For more information about this error, try `rustc --explain E0599`.
error: could not compile `trait-issue` (lib) due to previous error
I think it’s saying that rustc doesn’t think that ByteRecordsIter implements ExactSizeIterator but it does according to the docs. But it could be complaining about one of the other bounds it mentions, the error isn’t super clear.
So what does the error mean and how do I fix it?
>Solution :
You’re looking at the wrong struct — you want the docs for ByteRecordsIter, not ByteRecordIter (note the s!).
Presumably, ByteRecordsIter is not ExactSizeIterator because it doesn’t know its length (roughly, the number of lines in the file), while ByteRecordIter is because it does know the number of columns.
You probably need to read the rows of the file into some long-lived, fully-in-memory data structure like a Vec<ByteRecord> with let records = rdr.byte_records().collect::<Result<Vec<_>, _>>().unwrap(); before sampling.