I found this answer: https://stackoverflow.com/a/56436053/5884503 and I'm intersted in this part:
struct SlowData;
impl SlowData {
fn new(_initial: &str) -> SlowData {
thread::sleep(Duration::from_secs(1));
Self
}
fn next_block(&self) -> io::Result<&[u8]> {
thread::sleep(Duration::from_secs(1));
Ok(b"data")
}
}
fn stream(pool: ThreadPool) -> impl Stream<Item = io::Result<Vec<u8>>> {
let (mut tx, rx) = mpsc::channel(10);
pool.spawn(async move {
let sd = SlowData::new("dummy");
for _ in 0..3 {
let block = sd.next_block().map(|b| b.to_vec());
tx.send(block).await.expect("Unable to send block");
}
})
.expect("Unable to spawn thread");
rx
}
How is it possible that we can return -> io::Result<&[u8]>
? The reference is owned by the function next_block
, in Ok(b"data)
. You can see that it's created inside the function. How can the result be used outside of it? As I understood, in Rust, a reference cannot be copied, it can only be referenced, so I don't see how Ok(b"data")
could copy the reference to its inside.