rust学习记录-控制台整数读取

交互读取数字

fn main(){
    let mut index = String::new();
    use std::io;
    io::stdin().read_line(&mut index).expect("not a num");
    let trimmed = index.trim();
    match trimmed.parse::<usize>() {
        Ok(i) => println!("input:{}",i),
        Err(..) => println!("this was not an integer: {}", trimmed),
    }
}

启动时传入参数

fn main(){
    use std::env;
    let args: Vec<String> = env::args().collect();
    assert!(args.len()>1);//断言传入参数
    match args[1].parse::<usize>() {
        Ok(num) => println!("output:{}",num),
        Err(..) => println!("this was not an integer: {}",args[1]),
    }   
    
}

ps:以上代码原型来自与https://doc.rust-lang.org及stackoverflow

猜你喜欢

转载自my.oschina.net/u/3703365/blog/1789756