国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

Rust- 錯誤處理

這篇具有很好參考價值的文章主要介紹了Rust- 錯誤處理。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點擊"舉報違法"按鈕提交疑問。

Rust approaches error handling with the aim of being explicit about possible error conditions. It separates the concerns of “normal” return values and “error” return values by using a specific set of types for each concern. Rust’s primary tools for expressing these concepts are the Result and Option types, along with the unwrap method.

  1. The Result type: This is an enum that represents either successful (Ok) or unsuccessful (Err) computation. Functions that can fail generally return a Result variant.

    Here’s a simple example:

    fn divide(numerator: f64, denominator: f64) -> Result<f64, &str> {
        if denominator == 0.0 {
            Err("Cannot divide by zero")
        } else {
            Ok(numerator / denominator)
        }
    }
    

    In this case, if you try to divide by zero, the function will return an error wrapped in the Err variant. Otherwise, it will return the division result wrapped in the Ok variant.

  2. The Option type: This is another enum that represents a value that could be something (Some) or nothing (None). It’s often used when you have a situation where a value could be absent or present.

    For example:

    fn find_word_starting_with<'a, 'b>(sentence: &'a str, initial: &'b str) -> Option<&'a str> {
        for word in sentence.split_whitespace() {
            if word.starts_with(initial) {
                return Some(word);
            }
        }
        None
    }
    

    This function tries to find a word starting with a specific string in a sentence. If it finds such a word, it returns Some(word), otherwise, it returns None.

  3. The unwrap method: Both Option and Result types have an unwrap method, which is used to get the value out. If the instance of Option is a Some variant, unwrap will return the value inside the Some. If the instance is a None, unwrap will panic.

    Similarly, for Result, if the instance is an Ok, unwrap will return the value inside the Ok. If the instance is an Err, unwrap will panic.

    let maybe_number: Option<i32> = Some(42);
    println!("{}", maybe_number.unwrap()); // Prints 42
    
    let definitely_not_a_number: Option<i32> = None;
    println!("{}", definitely_not_a_number.unwrap()); // This will panic
    

    It’s generally advised to avoid using unwrap in most situations, as it can lead to your program crashing. Instead, you should handle errors appropriately using pattern matching or methods like unwrap_or, unwrap_or_else, expect, etc., which allow you to provide alternative values or actions in case of an error.

  4. The ? operator: This is a convenient way to propagate errors upwards in the call stack. When you use ? on a Result value, it does pretty much the same as a match expression would do: if the value is Ok, it unwraps it; if it’s Err, it returns it from the current function. This allows for more concise error handling.

fn main() {
    match foo() {
        Ok(_) => println!("Success"),
        Err(e) => println!("Error: {}", e),
    }
}

fn foo() -> Result<(), &'static str> {
    bar()?;
    Ok(())
}

fn bar() -> Result<(), &'static str> {
    Err("Some error")
}

In the foo function, bar()? will return the error from bar, thus ending the foo function early.

These are the basic building blocks of error handling in Rust. Rust also provides advanced features like creating your own error types, using the From trait for flexible error conversions, etc., but those are more advanced topics.文章來源地址http://www.zghlxwxcb.cn/news/detail-622684.html

use std::fs::File;

fn main() {
    panic!("出錯了");
    println!("Hello Rust");

    // panic 程序立即退出,退出的時候調(diào)用者拋出退出原因。

    // 數(shù)組越界
    let v = vec!["Rust", "Programming", "Language"];
    println!("{}", v[5]); // thread 'main' panicked at 'index out of bounds: the len is 3 but the index is 5'

    // 打開文件出錯
    let f = File::open("abc.txt");
    println!("{:?}", f); // Err(Os { code: 2, kind: NotFound, message: "系統(tǒng)找不到指定的文件。" })

    // unwrap expect
    let result = is_even(6).unwrap();
    println!("結(jié)果{}", result);

    let result = is_even(11).unwrap();
    println!("結(jié)果{}", result);

    // unwrap()是Result<T, E>的方法,實例上調(diào)用此方法時,如果是Ok,就返回Ok中的對象
    // 如果是Err枚舉,在運行時會panic

    // expect()接收msg::&str作為參數(shù),可以自定義報錯信息。
}

fn is_even(no: i32) -> Result<bool, String> {
    return if no % 2 == 0 {
        Ok(true)
    } else {
        Err("輸入的值不是偶數(shù)".to_string())
    };
}

到了這里,關(guān)于Rust- 錯誤處理的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實不符,請點擊違法舉報進(jìn)行投訴反饋,一經(jīng)查實,立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費用

相關(guān)文章

  • 30天拿下Rust之錯誤處理

    30天拿下Rust之錯誤處理

    概述 ????????在軟件開發(fā)領(lǐng)域,對錯誤的妥善處理是保證程序穩(wěn)定性和健壯性的重要環(huán)節(jié)。Rust作為一種系統(tǒng)級編程語言,以其對內(nèi)存安全和所有權(quán)的獨特設(shè)計而著稱,其錯誤處理機(jī)制同樣體現(xiàn)了Rust的嚴(yán)謹(jǐn)與實用。在Rust中,錯誤處理通常分為兩大類:不可恢復(fù)的錯誤和可

    2024年03月21日
    瀏覽(20)
  • Rust Web 全棧開發(fā)之 Web Service 中的錯誤處理

    數(shù)據(jù)庫 數(shù)據(jù)庫錯誤 串行化 serde 錯誤 I/O 操作 I/O 錯誤 Actix-Web 庫 Actix 錯誤 用戶非法輸入 用戶非法輸入錯誤 編程語言常用的兩種錯誤處理方式: 異常 返回值( Rust 使用這種) Rust 希望開發(fā)者顯式的處理錯誤,因此,可能出錯的函數(shù)返回Result 枚舉類型,其定義如下: 例子 在

    2024年02月07日
    瀏覽(22)
  • Rust之構(gòu)建命令行程序(三):重構(gòu)改進(jìn)模塊化和錯誤處理

    Rust之構(gòu)建命令行程序(三):重構(gòu)改進(jìn)模塊化和錯誤處理

    Windows 10 Rust 1.74.1 ? VS Code 1.85.1 這次創(chuàng)建了新的工程minigrep. 為了改進(jìn)我們的程序,我們將修復(fù)與程序結(jié)構(gòu)及其處理潛在錯誤的方式有關(guān)的四個問題。首先,我們的 main 函數(shù)現(xiàn)在執(zhí)行兩項任務(wù):解析參數(shù)和讀取文件。隨著我們程序的增長, main 處理的獨立任務(wù)的數(shù)量也會增加。隨

    2024年01月18日
    瀏覽(106)
  • Rust腐蝕申述教程Rust被辦申述處理

    Rust腐蝕申述教程Rust被辦申述處理

    玩Rust很難避免被辦,但有些被辦是理所當(dāng)。例如:開G、開宏或者其他作弊行為影響了游戲平衡,本指南主要針對綠色玩家被誤封的情況。 一、不同類型的封禁 首先要了解不同的封禁類型,并不是所有的封禁都是公平公正的,特別是國人在外服或者社區(qū)服游戲時經(jīng)常被辦出服

    2024年02月06日
    瀏覽(16)
  • Rust處理JSON

    Rust處理JSON

    基本操作 Cargo.toml: main.rs: 輸出為: 嵌套結(jié)構(gòu)體 warp [1] 返回不同的結(jié)構(gòu)(一般用枚舉來解決) 參考資料 [1] warp: https://github.com/seanmonstar/warp 本文由 mdnice 多平臺發(fā)布

    2024年02月11日
    瀏覽(19)
  • rust版本更新錯誤記錄:Os { code: 5, kind: PermissionDenied }

    使用 rustup update 更新 rust 版本時遇到錯誤: info: cleaning up downloads tmp directories thread ‘main’ panicked at ‘Unable to clean up C:UsersGrapeX.rustuptmp: Os { code: 5, kind: PermissionDenied, message: “拒絕訪問?!?}’, srcutilsutils.rs:650:13 stack backtrace: note: Some details are omitted, run with RUST_BACKTRACE=full

    2024年02月16日
    瀏覽(20)
  • RUST Rover 條件編譯 異常處理

    RUST Rover 條件編譯 異常處理

    會報異常 error: failed to parse manifest at C:UserstopmaRustroverProjectsuntitled2Cargo.toml 網(wǎng)上說明 這樣處理 https://course.rs/cargo/reference/features/intro.html RUST 圣經(jīng)里描述

    2024年04月09日
    瀏覽(20)
  • Rust中的高吞吐量流處理

    Rust中的高吞吐量流處理

    本篇文章主要介紹了Rust中流處理的概念、方法和優(yōu)化。作者不僅介紹了流處理的基本概念以及Rust中常用的流處理庫,還使用這些庫實現(xiàn)了一個流處理程序。 最后,作者介紹了如何通過測量空閑和阻塞時間來優(yōu)化流處理程序的性能,并將這些內(nèi)容同步至Twitter和blog。 此外,作

    2024年02月14日
    瀏覽(26)
  • Rust中的字符串處理及相關(guān)方法詳解

    在Rust中,字符串是一種非常重要的數(shù)據(jù)類型,而 String 類型則提供了對動態(tài)可變字符串的支持。本文將介紹一些常見的字符串處理方法以及相關(guān)示例代碼。 在Rust中,有多種方式創(chuàng)建字符串,以下是一些常見的例子: push_str()方法 push_str() 方法用于將一個字符串切片附加到 S

    2024年02月19日
    瀏覽(19)
  • 【Rust】——通過Deref trait將智能指針當(dāng)作常規(guī)引用處理

    ??博主現(xiàn)有專欄: ????????????????C51單片機(jī)(STC89C516),c語言,c++,離散數(shù)學(xué),算法設(shè)計與分析,數(shù)據(jù)結(jié)構(gòu),Python,Java基礎(chǔ),MySQL,linux,基于HTML5的網(wǎng)頁設(shè)計及應(yīng)用,Rust(官方文檔重點總結(jié)),jQuery,前端vue.js,Javaweb開發(fā),Python機(jī)器學(xué)習(xí)等 ??主頁鏈接: ????

    2024年04月26日
    瀏覽(23)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包