为什么 std::io::Read
中的方法,即read_to_end
, read_to_string
,和read_exact
获取缓冲区而不是返回结果?当前返回值为 Result<usize>
(或 Result<()>
),但是不能将其制成一个元组,也包含结果吗?
最佳答案
RFC 517讨论这些函数并描述了这些函数使用缓冲区而不是返回值的两个原因:
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.
对于第一点,可以使用关联函数 String::with_capacity
预先分配字符串。 。向量存在一个非常相似的函数: Vec::with_capacity
.
关于file - 为什么 std::io::Read 中的函数需要缓冲区?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44913851/