gpt4 book ai didi

file - 为什么 std::io::Read 中的函数需要一个缓冲区?

转载 作者:行者123 更新时间:2023-11-29 08:06:13 25 4
gpt4 key购买 nike

为什么 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com