File tree 2 files changed +53
-0
lines changed
2 files changed +53
-0
lines changed Original file line number Diff line number Diff line change @@ -24,5 +24,6 @@ in a controlled repository now.
24
24
* ` sum.rs ` : generic iterator sum example
25
25
* ` addy.rs ` : trait def/impl example
26
26
* ` bno-salad.rs ` : trait salad example from Blandy and Orendorff
27
+ * ` matmul.rs ` : example of overloading multiplication for matrices
27
28
* ` custom_sum.rs ` : sum example with custom ` Sum ` type
28
29
* ` phantom.rs ` : phantom type example
Original file line number Diff line number Diff line change
1
+ use std:: ops:: * ;
2
+
3
+ #[ derive( Debug , Clone , Copy ) ]
4
+ struct Matrix3 ( [ [ u64 ; 3 ] ; 3 ] ) ;
5
+
6
+ impl Mul for Matrix3 {
7
+ type Output = Matrix3 ;
8
+
9
+ fn mul ( self , Matrix3 ( rhs) : Self ) -> Self {
10
+ let Matrix3 ( lhs) = self ;
11
+ let mut result = [ [ 0 ; 3 ] ; 3 ] ;
12
+ for i in 0 ..3 {
13
+ for j in 0 ..3 {
14
+ for k in 0 ..3 {
15
+ result[ i] [ k] += lhs[ i] [ j] * rhs[ j] [ k] ;
16
+ }
17
+ }
18
+ }
19
+ Matrix3 ( result)
20
+ }
21
+ }
22
+
23
+ impl PartialEq for Matrix3 {
24
+ fn eq ( & self , & Matrix3 ( ref rhs) : & Matrix3 ) -> bool {
25
+ self . 0 == * rhs
26
+ }
27
+ }
28
+
29
+ const TTT : Matrix3 = Matrix3 (
30
+ [ [ 1 , 2 , 3 ] ,
31
+ [ 4 , 5 , 6 ] ,
32
+ [ 7 , 8 , 9 ] ]
33
+ ) ;
34
+
35
+ const ID : Matrix3 = Matrix3 (
36
+ [ [ 1 , 0 , 0 ] ,
37
+ [ 0 , 1 , 0 ] ,
38
+ [ 0 , 0 , 1 ] ]
39
+ ) ;
40
+
41
+ const MAGIC : Matrix3 = Matrix3 (
42
+ [ [ 6 , 1 , 8 ] ,
43
+ [ 7 , 5 , 3 ] ,
44
+ [ 2 , 9 , 4 ] ]
45
+ ) ;
46
+
47
+ fn main ( ) {
48
+ assert_eq ! ( TTT * ID , TTT ) ;
49
+ assert_eq ! ( ID * TTT , TTT ) ;
50
+ assert ! ( TTT * MAGIC != MAGIC * TTT ) ;
51
+ println ! ( "{:?}" , TTT * TTT ) ;
52
+ }
You can’t perform that action at this time.
0 commit comments