2017-01-16 50 views
3

我正試圖找到一個好方法將Option<String>轉換爲Option<i8>如何將選項<結果<T, Error>>轉換爲選項<T>而不打開它?

例如,

use std::str::FromStr; 

fn main() { 
    let some_option: Option<String> = Some("too".to_owned()); 
    let new_option: Option<i8> = some_option.map(|x| i8::from_str(x.as_str())); 
} 

我想我可以使用渦輪增壓魚顯式轉換類型,這樣是這樣的:

use std::str::FromStr; 

fn main() { 
    let some_option: Option<String> = Some("too".to_owned()); 
    let new_option: Option<i8> = some_option.map::<Option<i8>>(|x| i8::from_str(x.as_str())); 
} 

然而,編譯器指出,這是不正確數量的參數,所以我認爲這可能工作,但它不:

use std::str::FromStr; 

fn main() { 
    let some_option: Option<String> = Some("too".to_owned()); 
    let new_option: Option<i8> = some_option.map::<Option<i8>,i8::from_str>(); 
} 

回答

5

你可以我們e本ok()unwrap_or()功能:

fn test() -> Option<Result<u32,()>> { 
    Some(Ok(1)) 
} 

fn main() { 
    let x: Option<Result<_, _>> = test(); 
    println!("{:?}", x.map(|r| r.ok()).unwrap_or(None)); 
} 
5

而不是創造擺在首位的Option<Result<T, E>>的,你可以結合:

  1. Option::and_then,應用於封閉返回一個Option和變平的結果。

  2. Result::ok,它將Result轉換爲Option,丟棄該錯誤。

fn main() { 
    let some_option = Some("too".to_owned()); 
    let new_option = some_option.and_then(|x| x.parse::<u8>().ok()); 
} 

您可以使用相同的兩個工具來回答你直接問:

fn convert<T, E>(a: Option<Result<T, E>>) -> Option<T> { 
    a.and_then(Result::ok) 
} 
相關問題