gpt4 book ai didi

input - 在 Rust 中读取行

转载 作者:行者123 更新时间:2023-12-05 04:39:03 24 4
gpt4 key购买 nike

io::stdin().read_line(&mut input) 方法这样实现的原因是什么?为什么不直接返回带有适当错误或输入的结果?为什么要传递 &mut input?这种方法有什么优势吗?

最佳答案

这样做的巨大优势在于,因为您传递的是对现有 String 的可变引用,所以您可以重用缓冲区,或根据需要预先分配它:

// 2K is a good default buffer size, but definitely do
// analyze the situation and adjust its size accordingly
let mut buffer = String::with_capactity(2048);
// Lock our standard input to eliminate synchronization overhead (unlocks when dropped)
let mut stdin = io::stdin().lock();

// Read our first line.
stdin.read_line(&mut buffer)?;
// This is a stand-in for any function that takes an &str
process_line_1(&buffer);
// Discard the data we've read, but retain the buffer that we have
buffer.clear();

// Reading a second line will reuse the memory allocation:
stdin.read_line(&mut buffer)?;
process_line_2(&buffer)?;

记住:分配太多比分配太频繁要有效得多。由于 Rust 的借用规则(我的建议是有一个“缓存结构”,不同函数之间的缓冲区共享可能有点笨拙"为特定函数或 API 集合保留空的预分配缓冲区),但是如果您在一个函数中创建和销毁缓冲区,则设置此缓存所需的工作很少,并且从中获得不同的性能优势潜力像这样缓存分配。

此 API 的优点在于,它不仅能够以干净的方式重用缓冲区,而且还鼓励这样做。如果连续调用多个 .read_line(),为每个调用创建一个新缓冲区会立即让人感觉不对。 API设计,教你如何高效使用,二话不说。要点是,这个小技巧不仅提高了 Rust 中 I/O 代码的性能,它还试图引导初学者以这种方式设计他们自己的 API,尽管不幸的是,分配重用在第三方 API 中经常被忽视。 [需要引用]

关于input - 在 Rust 中读取行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70479516/

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