arrays - 从 rust 中的数组转换的字符串中删除额外的长度
问题描述
我正在尝试使用 tokio 学习 rust 中的异步。我试图通过使用 需要数组作为缓冲区的tokio::io::AsyncReadExt::Read从终端获取输入。但是当我将该缓冲区转换为字符串时,我无法将它与其他字符串进行比较,因为我认为它有额外的长度。
这是最少的代码:-
use std::process::Command;
use tokio::prelude::*;
use tokio::time;
async fn get_input(prompt: &str) -> String {
println!("{}", prompt);
let mut f = io::stdin();
let mut buffer = [0; 10];
// read up to 10 bytes
f.read(&mut buffer).await;
String::from_utf8((&buffer).to_vec()).unwrap()
}
async fn lol() {
for i in 1..5 {
let mut input = get_input("lol asks ").await;
input.shrink_to_fit();
print!("lol {} input = '{}' len = {}", i, input, input.len());
if input.eq("sl\n") {
let mut konsole = Command::new("/usr/bin/konsole");
konsole.arg("-e").arg("sl");
konsole.output().expect("some error happend");
}
}
}
#[tokio::main]
async fn main() {
let h = lol();
futures::join!(h);
}
如果我执行此代码,我会得到:-
lol asks
sl
lol 1 input = 'sl
' len = 10lol asks
这意味着字符串的长度为 10
解决方案
我在 Discord 人的帮助下解决了
我需要使用 f.read(...).await.unwrap() 返回的数字,否则,最后会有一些额外的零字节,这些字节不是通过读取返回的
let i = f.read(&mut buffer).await.unwrap() ;
String::from_utf8((&buffer[..i]).to_vec()).unwrap()
推荐阅读
- visual-studio-2019 - 更改 Visual Studio 2019 的搜索引擎
- c++ - C ++,如果某些条目重复,则输出所有可能的排列(递归算法)
- windows - Powershell检查用户是否是本地用户并且具有本地Windows机器上的用户名和密码的管理员权限(非活动目录)
- java - SystemProperties 类方法的替代方法及其在 java 或 kotlin 中的用法是什么?
- reactjs - 列内的反应路由器链接不会“填充”整个列
- sql-server - 如何通过 EF 检索自定义/用户定义列的值?
- javascript - 使用 flex-box 时如何保持图标居中?我有一个案例,我在一个页面中有 2 个图标,在另一个页面中有 3 个图标用于反应项目
- sql-server - 我的 Visual Studio 无法连接到 SQL Cluster Server
- c# - 如何从
并使用 Xamarin 从一页到另一页显示此文本? - c++ - 如何计算子字符串出现在字符串中的次数?