我刚刚开始学习 Rust,我正在努力处理生命周期。
我想要一个带有 a 的结构String,它将用于缓冲来自 stdin 的行。然后我想在结构上有一个方法,它从缓冲区返回下一个字符,或者如果该行中的所有字符都已被消耗,它将从标准输入读取下一行。
文档说 Rust 字符串不能按字符索引,因为 UTF-8 效率低下。当我按顺序访问字符时,使用迭代器应该没问题。但是,据我所知,Rust 中的迭代器与它们正在迭代的事物的生命周期相关联,我无法弄清楚如何将这个迭代器与String.
这是我想要实现的伪 Rust。显然它不会编译。
struct CharGetter {
/* Buffer containing one line of input at a time */
input_buf: String,
/* The position within input_buf of the next character to
* return. This needs a lifetime parameter. */
input_pos: std::str::Chars
}
impl CharGetter {
fn next(&mut self) -> Result<char, io::Error> {
loop {
match self.input_pos.next() {
/* If there is still a character left in …Run Code Online (Sandbox Code Playgroud) rust ×1