簡體   English   中英

如何指定綁定在作為結果的關聯類型上的特征?

[英]How can I specify a trait bound on an associated type that is a Result?

我正在嘗試編寫一個可以采用返回ResultStream的函數。 問題在於為Result的成功值指定邊界。

這是一個說明問題的示例(是的,它不會在沒有異步運行時的情況下運行,但這並不是真正的問題):

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;
    };
}

下面的編譯器錯誤是有道理的,因為Result沒有實現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`.

但是我試圖指定S的關聯Item實際上應該是Result失敗,因為Result不是特征:

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`.

如何指定我想要返回具有AsRef<str>值的ResultStream 我意識到我可能還需要為Err類型指定一些東西; 假設這是一個類似的語法。

等同關聯類型的語法是Trait<Assoc = Type>

所以:

async fn handle_stream<S, I, E>(mut stream: S)
where
    S: Stream<Item = Result<I, E>> + Unpin,
    I: AsRef<str>,
{
    // ...
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM