因为我是Rust的新手,所以我需要有关如何以惯用方式完成错误处理的指导。我发现错误处理样板真的很烦人。
我遇到了多个Option<T>
。
None
案例过于冗长。
例如,在Haskell中,您可以使用各种运算符链接可选值(Maybe
):fmap
,<*>
,>>=
等:< / p>
f x = x * x
g x = x ++ x
main = print $ g <$> show <$> f <$> Just 2
在Rust中看起来不可能。我正在尝试将两个字符的卡片串解析为结构Card
:
const FACES: &'static str = "23456789TJQKA";
const SUITS: &'static str = "CDHS";
enum Face { /* ... */ }
enum Suit { C, D, H, S }
struct Card {
face: Face,
suit: Suit
}
impl FromStr for Card {
type Err = ();
fn from_str(x: &str) -> Result<Self, Self::Err> {
let mut xs = x.chars();
let a = chain(xs.next(), |x| FACES.find(x), Face::from_usize);
let b = chain(xs.next(), |x| SUITS.find(x), Suit::from_usize);
if let (Some(face), Some(suit)) = (a, b) {
Ok(Card::new(face, suit))
} else {
Err(())
}
}
}
这段代码在Haskell中看起来像这样:
import Data.List (elemIndex)
x = Just 'C'
suits = "CDHS"
data Suit = C | D | H | S deriving Show
fromInt 0 = C
find = flip elemIndex
main = print $ x >>= find suits >>= return . fromInt
感谢通过>>=
链接Haskell使得操作monad的内部值成为可能(并且很容易!)。为了达到接近的目的,我必须编写chain
函数,这看起来非常单一:
fn join<T>(x: Option<Option<T>>) -> Option<T> {
if let Some(y) = x {
y
} else {
None
}
}
fn bind<A, B, F>(x: Option<A>, f: F) -> Option<B>
where
F: FnOnce(A) -> Option<B>,
{
join(x.map(f))
}
fn chain<A, B, C, F, G>(x: Option<A>, f: F, g: G) -> Option<C>
where
F: FnOnce(A) -> Option<B>,
G: FnOnce(B) -> Option<C>,
{
bind(bind(x, f), g)
}
答案 0 :(得分:11)
如上所述,Option
和Result
上有吨的实用工具方法。此外,try运算符(?
)也可用于“返回失败或解包结果”的极为常见的情况
我为FromStr
和Face
实施Suit
。您的代码将如下所示:
impl FromStr for Card {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
let face = s[0..1].parse()?;
let suit = s[1..2].parse()?;
Ok(Card { face, suit })
}
}
如果您没有/不能,您可以使用Option
上的现有方法。您没有定义Foo::from_usize
,因此我假设返回Foo
,因此会使用map
:
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut c = s.chars();
let face = c
.next()
.and_then(|c| FACES.find(c))
.map(Face::from_usize)
.ok_or(())?;
let suit = c
.next()
.and_then(|c| SUITS.find(c))
.map(Suit::from_usize)
.ok_or(())?;
Ok(Card { face, suit })
}
这两个路径都允许您有有用的错误,例如枚举,让您知道套装/面部是否缺失/无效。错误类型()
对消费者无用。
您还可以定义Suit::from_char
和Face::from_char
,而不是泄漏数组的实现。
全部放在一起:
impl Suit {
fn from_char(c: char) -> Option<Self> {
use Suit::*;
[('c', C), ('d', D), ('h', H), ('s', S)]
.iter()
.cloned()
.find(|&(cc, _)| cc == c)
.map(|(_, s)| s)
}
}
enum Error {
MissingFace,
MissingSuit,
InvalidFace,
InvalidSuit,
}
impl FromStr for Card {
type Err = Error;
fn from_str(x: &str) -> Result<Self, Self::Err> {
use Error::*;
let mut xs = x.chars();
let face = xs.next().ok_or(MissingFace)?;
let face = Face::from_char(face).ok_or(InvalidFace)?;
let suit = xs.next().ok_or(MissingSuit)?;
let suit = Suit::from_char(suit).ok_or(InvalidSuit)?;
Ok(Card { face, suit })
}
}
fn join<T>(x: Option<Option<T>>) -> Option<T>
这是x.and_then(|y| y)
fn bind<A, B, F>(x: Option<A>, f: F) -> Option<B>
where
F: FnOnce(A) -> Option<B>,
这是x.and_then(f)
fn chain<A, B, C, F, G>(x: Option<A>, f: F, g: G) -> Option<C>
where
F: FnOnce(A) -> Option<B>,
G: FnOnce(B) -> Option<C>,
这是x.and_then(f).and_then(g)
另见:
答案 1 :(得分:6)
好像你想要Option::and_then
:
pub fn and_then<U, F>(self, f: F) -> Option<U>
where
F: FnOnce(T) -> Option<U>
示例:
fn sq(x: u32) -> Option<u32> { Some(x * x) }
fn nope(_: u32) -> Option<u32> { None }
assert_eq!(Some(2).and_then(sq).and_then(sq), Some(16));
assert_eq!(Some(2).and_then(sq).and_then(nope), None);
assert_eq!(Some(2).and_then(nope).and_then(sq), None);
assert_eq!(None.and_then(sq).and_then(sq), None);
答案 2 :(得分:4)
除了其他答案之外,您还可以查看mdo或map_for等monadic表达包。例如map_for
:
fn from_str(x: &str) -> Result<Self, Self::Err> {
let mut xs = x.chars();
map_for!{
ax <- xs.next();
f <- FACES.find(ax);
a <- Face::from_usize(f);
bx <- xs.next();
s <- SUITS.find(bx);
b <- Suit::from_usize (s);
=> Card::new(a, b) }
.ok_or(Err(()))
}
完全披露:我是map_for
crate的作者。
答案 3 :(得分:0)
Maybe
- Rust Result
中的monadic链接由the try!
macro完成。应该看起来像
fn from_str(x: &str) -> Result<Self, Self::Err> {
let mut xs = x.chars();
let a = try!(chain(xs.next(), |x| FACES.find(x), Face::from_usize));
let b = try!(chain(xs.next(), |x| SUITS.find(x), Suit::from_usize));
Ok(Card::new(face, suit))
}