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及stackoverflowthis

相關文章
相關標籤/搜索