I'm trying to write a function that can take a Stream that returns Results. The trouble is in specifying boundaries for the success values of the Result.
This is an example that illustrates the problem (yes, it won't run without an async runtime, but that's not really the issue at hand):
use std::{pin::Pin, task::{Context, Poll}};
use futures::{Stream, StreamExt};
struct Data;
impl Stream for Data {
type Item = Result<String, std::io::Error>;
#[inline]
fn poll_next(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Option<Self::Item>> {
Poll::Ready(Some(Ok("Hello".to_owned())))
}
}
async fn handle_stream<S>(mut stream: S) where S: Stream + Unpin, <S as Stream>::Item: AsRef<str> {
while let Some(item) = stream.next().await {
// TODO
}
}
fn main() {
let mut data = Data{};
async move {
handle_stream(data).await;
};
}
The compiler error below makes sense, since Result does not implement AsRef:
error[E0277]: the trait bound `Result<String, std::io::Error>: AsRef<str>` is not satisfied
--> src/main.rs:24:5
|
24 | handle_stream(data).await;
| ^^^^^^^^^^^^^ the trait `AsRef<str>` is not implemented for `Result<String, std::io::Error>`
|
note: required by a bound in `handle_stream`
--> src/main.rs:15:88
|
15 | async fn handle_stream<S>(mut stream: S) where S: Stream + Unpin, <S as Stream>::Item: AsRef<str> {
| ^^^^^^^^^^ required by this bound in `handle_stream`
For more information about this error, try `rustc --explain E0277`.
But my attempts to specify that the associated Item for S should actually be a Result fail, since Result is not a trait:
error[E0404]: expected trait, found enum `Result`
--> src/main.rs:15:88
|
15 | async fn handle_stream<S>(mut stream: S) where S: Stream + Unpin, <S as Stream>::Item: Result<AsRef<str>> {
| ^^^^^^^^^^^^^^^^^^ not a trait
For more information about this error, try `rustc --explain E0404`.
How can I specify that I want Streams that return Results that have AsRef<str> values? I realize I will likely need to specify something for the Err type as well; assuming that's a similar syntax.