如何匹配从标准输入读取的字符串? [英] How do I match on a string read from standard input?

查看:50
本文介绍了如何匹配从标准输入读取的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在学习 Rust 的练习中,我正在尝试一个简单的程序,该程序将接受您的姓名,然后在有效时打印您的姓名.

In an exercise to learn Rust, I'm trying a simple program that will accept your name, then print your name if it's Valid.

只有Alice"和Bob"是有效的名字.

use std::io;

fn main() {
    println!("What's your name?");
    let mut name = String::new();

    io::stdin().read_line(&mut name)
    .ok()
    .expect("Failed to read line");

    greet(&name);
}

fn greet(name: &str) {
    match name {
        "Alice" => println!("Your name is Alice"),
        "Bob"   => println!("Your name is Bob"),
        _ => println!("Invalid name: {}", name),
    }
}

当我cargo run这个main.rs文件时,我得到:

When I cargo run this main.rs file, I get:

What's your name?
Alice
Invalid name: Alice

现在,我的猜测是,因为Alice"的类型是 &'static strname 的类型是 &str, 可能是匹配不正确...

Now, my guess is, because "Alice" is of type &'static str and name is of type &str, maybe it's not matching correctly...

推荐答案

我敢打赌这不是由类型不匹配引起的.我打赌有一些不可见的字符(在这种情况下是新行).为了实现您的目标,您应该修剪输入字符串:

I bet that it isn't caused by type mismatch. I place my bet on that there are some invisible characters (new line in this case). To achieve your goal you should trim your input string:

match name.trim() {
    "Alice" => println!("Your name is Alice"),
    "Bob"   => println!("Your name is Bob"),
    _ => println!("Invalid name: {}", name),
}

这篇关于如何匹配从标准输入读取的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆