Rust futures:修订间差异

来自WHY42
Riguz留言 | 贡献
标签2017版源代码编辑
Riguz留言 | 贡献
标签2017版源代码编辑
第10行: 第10行:
     }
     }
}
}
</syntaxhighlight>


You could unwarp the result of error by calling `unwrap` or `unwrap_err`,
be aware that it will panic if not matched:
<syntaxhighlight lang="rust">
fn main() {
fn main() {
     let site: String = String::from("Google");
     let google: String = String::from("Google");
     let url: String = get_url(&site).unwrap();
     let unknown: String = String::from("Unknown");
     println!("Url of {} is {}", site, url);
 
    let url = get_url(&google).unwrap();
     println!("Url of {} is {}", google, url);
     // Url of Google is https://google.com
     // Url of Google is https://google.com
}
</syntaxhighlight>


If result is Err, then unwrap will panic:
    // panic
    // let url = get_url(&unknown).unwrap();
 
    let err = get_url(&unknown).unwrap_err();
    println!("error code is {}", err);
    // error code is 2


<syntaxhighlight lang="rust">
     // panic
fn main() {
     //let err = get_url(&google).unwrap_err();
     let site: String = String::from("Unknown");
     let url: String = get_url(&site).unwrap();
    println!("Url of {} is {}", site, url);
    // thread 'main' panicked at src/main.rs:27:38:
    // called `Result::unwrap()` on an `Err` value: 2
}
}
</syntaxhighlight>
</syntaxhighlight>
[[Category:Rust]]
[[Category:Rust]]

2024年12月28日 (六) 11:36的版本

Result

Unwrap

fn get_url(name: &String) -> Result<String, i32> {
    match name.as_str() {
        "Google" => Ok(String::from("https://google.com")),
        "Bing" => Ok(String::from("https://bing.com")),
        "" => Err(1),
        _ => Err(2),
    }
}

You could unwarp the result of error by calling `unwrap` or `unwrap_err`, be aware that it will panic if not matched:

fn main() {
    let google: String = String::from("Google");
    let unknown: String = String::from("Unknown");

    let url = get_url(&google).unwrap();
    println!("Url of {} is {}", google, url);
    // Url of Google is https://google.com

    // panic
    // let url = get_url(&unknown).unwrap();

    let err = get_url(&unknown).unwrap_err();
    println!("error code is {}", err);
    // error code is 2

    // panic
    //let err = get_url(&google).unwrap_err();
}