【问题标题】:How does tokio::net::TcpStream implement tokio::prelude::Stream?tokio::net::TcpStream 是如何实现 tokio::prelude::Stream 的?
【发布时间】:2019-05-29 19:48:55
【问题描述】:

tokio.rs 文档中,我们看到以下 sn-p

// split the socket stream into readable and writable parts
let (reader, writer) = socket.split();
// copy bytes from the reader into the writer
let amount = io::copy(reader, writer);

我假设split 确实是Stream::split,但我无法弄清楚这个特征如何应用于TcpStream,因为流页面没有提到TcpStream,反之亦然。

【问题讨论】:

  • “如何”是什么意思?几乎所有的特征都以相同的方式为一个类型实现:impl Trait for Type { ... }。有时该代码是由宏或其他什么生成的,但最终是相同的。
  • The documentation shows 为一个类型实现了哪些特征以及它们提供了哪些方法。
  • 你可以测试一个类型是否实现了一个特征:How to enforce that a type implements a trait at compile time?
  • 也许我的编辑会帮助你理解我在问什么。我知道特征是如何定义的。我的问题是,鉴于两者之间没有明显的相似之处,我该如何建立该链接?它是一揽子实现吗?我不知道。
  • 当我链接到the documentation for TcpStream时,你有没有在页面上搜索方法split

标签: rust traits rust-tokio


【解决方案1】:

tokio::net::TcpStream 实现AsyncRead

AsyncRead 提供的方法之一是split()

fn split(self) -> (ReadHalf<Self>, WriteHalf<Self>)
where
    Self: AsyncWrite, 

所以在这种情况下,它不是您的问题所建议的Stream::split,因为根据您的观察,tokio::net::TcpStream 不是Stream 的实现者。

【讨论】:

  • 如果你明确列出你为解决这个问题而采取的确切步骤可能会很好,这样 OP 就可以将逻辑应用于其他任务。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-18
  • 2020-08-06
  • 1970-01-01
  • 2020-08-01
  • 2023-02-18
  • 1970-01-01
相关资源
最近更新 更多