首页 > 其他分享 >[Rust] Using ? operator in the main function

[Rust] Using ? operator in the main function

时间:2024-03-01 16:26:18浏览次数:29  
标签:function tokens item cost let operator Using main

use std::num::ParseIntError;

fn main() -> Result<(), ParseIntError> {
    let mut token = 100;
    let pretend_user_input = "8";
    
    let cost = total_cost(pretend_user_input)?; // <-- use ? in main function
    
    if cost > tokens {
        println!("You can't affort that many!");
    } else {
        println!("You now have {} tokens.", tokens);
    }

    Ok(())
}

pub fn total_cost(item_quantity: &str) -> Result<i32, ParseIntError> {
    let processing_fee = 1;
    let cost_per_item = 5;
    let qty = item_quantity.parse::<i32>()?;
    
    Ok(qty * cost_per_item + processing_fee)    
}

 

标签:function,tokens,item,cost,let,operator,Using,main
From: https://www.cnblogs.com/Answer1215/p/18047323

相关文章