RustDay05------Exercise[51-60]

51.使用?当作错误处理符

? 是 Rust 中的错误处理操作符。通常用于尝试解析或执行可能失败的操作,并在出现错误时提前返回错误,以避免程序崩溃或出现未处理的错误。

具体来说,? 用于处理 Result 或 Option 类型的返回值。

rust 复制代码
// errors2.rs
// Say we're writing a game where you can buy items with tokens. All items cost
// 5 tokens, and whenever you purchase items there is a processing fee of 1
// token. A player of the game will type in how many items they want to buy,
// and the `total_cost` function will calculate the total number of tokens.
// Since the player typed in the quantity, though, we get it as a string-- and
// they might have typed anything, not just numbers!

// Right now, this function isn't handling the error case at all (and isn't
// handling the success case properly either). What we want to do is:
// if we call the `parse` function on a string that is not a number, that
// function will return a `ParseIntError`, and in that case, we want to
// immediately return that error from our function and not try to multiply
// and add.

// There are at least two ways to implement this that are both correct-- but
// one is a lot shorter!
// Execute `rustlings hint errors2` or use the `hint` watch subcommand for a hint.

// I AM NOT DONE

use std::num::ParseIntError;

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

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn item_quantity_is_a_valid_number() {
        assert_eq!(total_cost("34"), Ok(171));
    }

    #[test]
    fn item_quantity_is_an_invalid_number() {
        assert_eq!(
            total_cost("beep boop").unwrap_err().to_string(),
            "invalid digit found in string"
        );
    }
}

52.在main函数中需要对ParseIntError进行Err匹配

这题只能这么理解,具体原理没翻到

rust 复制代码
// errors3.rs
// This is a program that is trying to use a completed version of the
// `total_cost` function from the previous exercise. It's not working though!
// Why not? What should we do to fix it?
// Execute `rustlings hint errors3` or use the `hint` watch subcommand for a hint.

// I AM NOT DONE

use std::num::ParseIntError;

fn main() {
    let mut tokens = 100;
    let pretend_user_input = "8";

    // let cost = total_cost(pretend_user_input)?;

    // if cost > tokens {
    //     println!("You can't afford that many!");
    // } else {
    //     tokens -= cost;
    //     println!("You now have {} tokens.", tokens);
    // }
    match total_cost(pretend_user_input) {
        Ok(cost) =>{
            if cost > tokens {
                println!("You can't afford that many!");
            } else {
                tokens -= cost;
                println!("You now have {} tokens.", tokens);
            }
        }
        Err(message) => {
            
        }
    }
}

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)
}
相关推荐
遇码12 小时前
给 Rust 桌面应用做双击安装包:Windows NSIS setup.exe + macOS DMG 的完整做法
人工智能·windows·ai·rust·大模型
GitCode官方15 小时前
本期精选 Rust 开源项目推荐
开发语言·rust·开源·g-star·atomgit
nezuko3518 小时前
用 AI 把代码改写成 Rust 之后,怎么证明它没改坏?我做了个开源工具
rust
爆米花byh2 天前
在RockyLinux9环境下安装Rust1.100.0环境
linux·rust
hai3152475432 天前
阶乘分层关系模型存储文本与表格
数据结构·算法·rust·排序算法·线性回归
Shota Kishi2 天前
Solana Stream SDK 的 UDP Shred 接收:data-only 与 recover 两种模式的取舍与实测
rust·区块链·solana
tomatohug2 天前
Tauri v2 实战:做一个贴在任何输入框上的提示词优化助手
rust
Zenova EdgeOS2 天前
Rust 数据库实战:工业边缘场景下的 sqlx
数据库·oracle·rust·边缘计算·工业网关
用户46043852250863 天前
关于paimon- rust的学习 --- Table(一)
大数据·rust
Kapaseker3 天前
快 18 倍?Laravel Rust 才是 Laravel 的未来
rust