我的实现

一个满足题意的实现

use std::io::{self, Write};
fn main() {
    print!("What is the input string?");
    io::stdout().flush().unwrap();
    let mut input = String::new();
    std::io::stdin().read_line(&mut input).expect(
        "Failed to read line",
    );
    println!("{} has {} characters.", input, input.len());
}

学到了什么

您可以通过增加一个循环来保证用户的确输入了内容。

use std::io::{self, Write};
fn main() {
    print!("What is the input string?");
    io::stdout().flush().unwrap();
    let mut input = String::new();
    std::io::stdin().read_line(&mut input).expect(
        "Failed to read line",
    );
    while input.len() == 0 {
        std::io::stdin().read_line(&mut input).expect(
            "Failed to read line",
        );
    }
    println!("{} has {} characters.", input, input.len());
}

当然这也不完全是一个好的实践。

use std::io::{self, Write};
fn main() {
    print!("What is the input string?");
    io::stdout().flush().unwrap();
    let mut input = String::new();
    loop {
        std::io::stdin().read_line(&mut input).expect(
            "Failed to read line",
        );
        if input.len() != 0 {
            break;
        }
        println!("Please enter the content.");
    }
    println!("{} has {} characters.", input, input.len());
}

这里使用了 loop 循环达到了一种好的实践,因为到现在为止 Rust 中还没有像 C 语言中那样的 do 循环。后面的两个程序都不能在 play 里面得到满意的结果。因为 play 里面不能输入。所以会导致死循环。