1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
//! A simple `Either` structure
//!
//! This structure is in effect isomorphic with `Result`, but does not have certain traits
//! implemented. Personally I think this is the better choice for expressing something which is not
//! really a `Result`.

use std::fmt::{Debug, Formatter};

pub enum Either<T1, T2> {
    Left(T1),
    Right(T2)
}

impl<E1, E2> Debug for Either<E1, E2>
    where E1: Debug,
          E2: Debug
{
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match &self {
            Either::Left(left) => {
                write!(f, "Left(")?;
                left.fmt(f)?;
                write!(f, ")")
            },
            Either::Right(right) => {
                write!(f, "Right(")?;
                right.fmt(f)?;
                write!(f, ")")
            }
        }
    }
}

#[cfg(test)]
mod test {
    use crate::either::Either;

    #[test]
    fn test_either() {
        let e1: Either<i32, String> = Either::Left(114);
        let e2: Either<i32, String> = Either::Right("514".to_string());

        eprintln!("e1 = {:?}, e2 = {:?}", e1, e2);

        if let Either::Left(num) = e1 {
            assert_eq!(num, 114);
        } else {
            unreachable!();
        }

        if let Either::Right(s) = e2 {
            assert_eq!(s, "514");
        } else {
            unreachable!();
        }
    }
}