Skip to main content

core/num/
complex.rs

1use crate::ops::{Add, Sub};
2
3/// A complex number.
4#[derive(Clone, Copy, Debug, PartialEq, Eq)]
5#[unstable(feature = "complex_numbers", issue = "154023")]
6#[repr(C)]
7#[lang = "complex"]
8pub struct Complex<T> {
9    /// The real component.
10    pub re: T,
11    /// The imaginary component.
12    pub im: T,
13}
14
15#[unstable(feature = "complex_numbers", issue = "154023")]
16impl<T> Complex<T> {
17    /// Create a new complex number from a real and imaginary component.
18    #[must_use]
19    pub fn new(re: T, im: T) -> Complex<T> {
20        Complex { re, im }
21    }
22}
23
24#[unstable(feature = "complex_numbers", issue = "154023")]
25impl<T: Add> Add<Self> for Complex<T> {
26    type Output = Complex<T::Output>;
27
28    fn add(self, rhs: Self) -> Self::Output {
29        Complex::new(self.re + rhs.re, self.im + rhs.im)
30    }
31}
32
33#[unstable(feature = "complex_numbers", issue = "154023")]
34impl<T: Add<Output = T>> Add<T> for Complex<T> {
35    type Output = Complex<T::Output>;
36
37    fn add(self, rhs: T) -> Self::Output {
38        Complex::new(self.re + rhs, self.im)
39    }
40}
41
42#[unstable(feature = "complex_numbers", issue = "154023")]
43impl<T: Sub> Sub<Self> for Complex<T> {
44    type Output = Complex<T::Output>;
45
46    fn sub(self, rhs: Self) -> Self::Output {
47        Complex::new(self.re - rhs.re, self.im - rhs.im)
48    }
49}
50
51#[unstable(feature = "complex_numbers", issue = "154023")]
52impl<T: Sub<Output = T>> Sub<T> for Complex<T> {
53    type Output = Complex<T::Output>;
54
55    fn sub(self, rhs: T) -> Self::Output {
56        Complex::new(self.re - rhs, self.im)
57    }
58}