[Rust] Using ? operator in the main function

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)    
}

 

posted @   Zhentiw  阅读(1)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2023-03-01 [Typescript] Clean type
2020-03-01 [Debug] debug module
2020-03-01 [CLI] Create a Hybrid Single-Multi Command Node.js CLI with Oclif and TypeScript
2020-03-01 [CLI] Convert a Single Command CLI into a Multi Command CLI with Oclif and TypeScript
2020-03-01 [CLI] Create a Single-Command Node.js CLI with Oclif, TypeScript and Yarn Workspaces
2020-03-01 [Custom CLI] Develop and Publish a Node.js CLI from Scratch
2019-03-01 [Compose] 21. Apply Natural Transformations in everyday work
点击右上角即可分享
微信分享提示