为什么 Read::read_to_string() return 不是字符串?

Why doesn't Read::read_to_string() return the string?

Read trait, many functions/methods take a buf: &mut XXX as (one of the) parameter(s) and return Result<usize>. For example, read_to_string()中将buf: &mut String作为参数之一和returns Result<usize>.

因为我来自多种语言,所以所谓的 现代 语言通常 return read_string() 函数调用的字符串。 Rust 中 Read trait 的设计有点让我震惊,因为它不是 return 字符串,而是 将它作为参数(类似于C或其他更原始的语言)。

我知道 return 值 (Result) 用于指示读取是否成功,它可以传递给 match 表达式。 (我以前学过Lisp和Go,所以我不质疑这种设计。)

为什么核心开发者没有把这个特性设计成"returning the string together with the error message"?

比如为什么不这样设计:

fn read(&mut self) -> Result<String> { ... }

String也包含了长度,所以用户可以在需要的时候通过调用.len()来获取长度。如果他愿意,用户可以将它连接到任何其他 String,但关键是在调用此函数之前不需要创建/拥有一个。

像现在这样设计这个特征有什么特别的原因吗?

p.s。我仍在学习 Rust(通过关注 The Rust Programming Language),并且在阅读第一版的大部分内容后正在阅读第二版。如果上面的代码有任何错误(尤其是在处理生命周期时),请纠正我。

我不知道真正的原因,但有一些好处:

  • 您可以控制 String 的分配方式。您可以从池中取出它,重新使用它等。
  • 您可以从多个 read_to_string(或类似)调用中读取同一个字符串。无需连接字符串
  • 结果字符串的大小(在作为参数传递的情况下)不会告诉你读取了多少字节(因为String可以是non-empty),这就是为什么usizeResult
  • 中返回

签名

fn read_to_string(&mut self) -> Result<String> { ... }

如果来自高级语言,可能看起来更自然,但它无法控制 String 及其分配。

RFC 517 (IO reform) 状态(强调我的):

The read_to_end and read_to_string methods now take explicit buffers as input. This has multiple benefits:

  • Performance. When it is known that reading will involve some large number of bytes, the buffer can be preallocated in advance.

  • "Atomicity" concerns. For read_to_end, it's possible to use this API to retain data collected so far even when a read fails in the middle. For read_to_string, this is not the case, because UTF-8 validity cannot be ensured in such cases; but if intermediate results are wanted, one can use read_to_end and convert to a String only at the end.

在 Rust 1.0 之前,Reader::read_to_string做了return一个String。这是一个深思熟虑的决定。

可以创建 Read::read_to_string 的 "on top" 函数,但反之则不然。标准库中的代码需要非常灵活。