首页
随机
最近更改
特殊页面
社群首页
参数设置
关于WHY42
免责声明
WHY42
搜索
用户菜单
登录
欢迎来到Riguz的小站!这是一个私人wiki,用来记录一些我的笔记。
查看“︁Rust futures”︁的源代码
←
Rust futures
因为以下原因,您没有权限编辑该页面:
您请求的操作仅限属于该用户组的用户执行:
用户
您可以查看和复制此页面的源代码。
= Result = == Unwrap == <syntaxhighlight lang="rust"> 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), } } </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() { 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(); } </syntaxhighlight> You can set default value if unwrap failed, thus no panic: <syntaxhighlight lang="rust"> let url1 = get_url(&google).unwrap_or_default(); let url2 = get_url(&unknown).unwrap_or_default(); let url3 = get_url(&unknown).unwrap_or(String::from("<Unknown url>")); println!("Url of {} is {}", google, url1); println!("Url of {} is {}", unknown, url2); println!("Url of {} is {}", unknown, url3); //Url of Google is https://google.com //Url of Unknown is //Url of Unknown is <Unknown url> </syntaxhighlight> `unwrap_or_else` accepts a function to convert error to result type: <syntaxhighlight lang="rust"> let url2 = get_url(&unknown).unwrap_or_else(|err| format!("Unknown url, error code={}!", err)); // Url of Unknown is Unknown url, error code=2! </syntaxhighlight> [[Category:Rust]]
返回
Rust futures
。