首页 > 解决方案 > 从 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

标签: arraysstringasynchronousrust

解决方案


我在 Discord 人的帮助下解决了

我需要使用 f.read(...).await.unwrap() 返回的数字,否则,最后会有一些额外的零字节,这些字节不是通过读取返回的

let i = f.read(&mut buffer).await.unwrap() ;

String::from_utf8((&buffer[..i]).to_vec()).unwrap()

推荐阅读