Rust程序I/O行为异常求助:输入exit无法正常退出问题排查
Rust简易键值存储程序exit命令无法退出的问题修复
核心问题:字符串未清空导致输入内容拼接
你代码里的operation、key、value都是在main函数开头声明的可变字符串,每次调用read_line时,新输入的内容是追加到原有字符串末尾,而不是覆盖。比如第一次输入put后,operation里的内容是"put\n",trim后得到"put";当你后续输入exit时,read_line会把"exit\n"追加进去,operation变成"put\nexit\n",trim后是"put\nexit",自然和"exit"不匹配,导致无法触发退出逻辑,还会输出无效命令提示。
修复步骤
- 每次循环前清空操作字符串
在loop内部,每次读取操作命令前,先清空operation:
loop { operation.clear(); // 新增这行 println!("what do you wanna do?"); stdin() .read_line(&mut operation) .expect("could not parse input"); // ... 后续代码不变 }
- 清空key和value变量的旧内容
在读取key或value前,同样需要清空原有内容,避免之前的输入残留:
- 在
put分支里,读取key前添加key.clear();,读取value前添加value.clear();:
if operation == operations.0 { println!("enter your key"); key.clear(); // 新增 stdin() .read_line(&mut key) .expect("could not parse the input"); let key = key.trim(); println!("enter your value"); value.clear(); // 新增 stdin() .read_line(&mut value) .expect("could not parse the input"); // ... 后续代码不变 }
- 在
get分支里,读取key前添加key.clear();:
} else if operation == operations.1 { println!("enter your key"); key.clear(); // 新增 stdin() .read_line(&mut key) .expect("could not parse the input"); // ... 后续代码不变 }
- 修复get函数的返回值错误
当前get函数返回的是key而不是对应的value,因为split(',').next()取的是分割后的第一个元素(key),需要改为取第二个元素;同时该函数仅读取数据,无需可变引用:
fn get(db: &Vec<String>, key: &str) -> String { for data in db { let mut parts = data.split(','); let stored_key = parts.next().expect("error while parsing the key"); if stored_key == key { return parts.next().expect("error while parsing the value").to_string(); } } String::from("404") }
修复后的程序行为
修改后,输入exit会正常触发break退出循环,get命令也能正确返回对应key的value值,不会再出现输入内容拼接的问题。
内容的提问来源于stack exchange,提问作者Mr. Cob
相关产品推荐
相关产品推荐

