1use crate::ops::{Add, Neg, Sub};
2
3#[derive(Clone, Copy, Debug, PartialEq, Eq)]
5#[unstable(feature = "complex_numbers", issue = "154023")]
6#[repr(C)]
7#[lang = "complex"]
8pub struct Complex<T> {
9 pub re: T,
11 pub im: T,
13}
14
15#[unstable(feature = "complex_numbers", issue = "154023")]
16impl<T> Complex<T> {
17 #[must_use]
19 pub const fn new(re: T, im: T) -> Complex<T> {
20 Complex { re, im }
21 }
22}
23
24#[unstable(feature = "complex_numbers", issue = "154023")]
25impl<T: Default> Default for Complex<T> {
26 fn default() -> Self {
27 Self { re: Default::default(), im: Default::default() }
28 }
29}
30
31#[unstable(feature = "complex_numbers", issue = "154023")]
32impl<T> Complex<T>
33where
34 T: Neg<Output = T>,
35{
36 #[must_use]
41 pub fn conjugate(self) -> Self {
42 Complex { re: self.re, im: -self.im }
43 }
44}
45
46#[unstable(feature = "complex_numbers", issue = "154023")]
47impl<T: Neg> Neg for Complex<T> {
48 type Output = Complex<T::Output>;
49
50 fn neg(self) -> Self::Output {
55 Complex::new(-self.re, -self.im)
56 }
57}
58
59#[unstable(feature = "complex_numbers", issue = "154023")]
60impl<T: Add> Add<Self> for Complex<T> {
61 type Output = Complex<T::Output>;
62
63 fn add(self, rhs: Self) -> Self::Output {
64 Complex::new(self.re + rhs.re, self.im + rhs.im)
65 }
66}
67
68#[unstable(feature = "complex_numbers", issue = "154023")]
69impl<T: Add<Output = T>> Add<T> for Complex<T> {
70 type Output = Complex<T::Output>;
71
72 fn add(self, rhs: T) -> Self::Output {
73 Complex::new(self.re + rhs, self.im)
74 }
75}
76
77#[unstable(feature = "complex_numbers", issue = "154023")]
78impl<T: Sub> Sub<Self> for Complex<T> {
79 type Output = Complex<T::Output>;
80
81 fn sub(self, rhs: Self) -> Self::Output {
82 Complex::new(self.re - rhs.re, self.im - rhs.im)
83 }
84}
85
86#[unstable(feature = "complex_numbers", issue = "154023")]
87impl<T: Sub<Output = T>> Sub<T> for Complex<T> {
88 type Output = Complex<T::Output>;
89
90 fn sub(self, rhs: T) -> Self::Output {
91 Complex::new(self.re - rhs, self.im)
92 }
93}