File tree 2 files changed +61
-0
lines changed
2 files changed +61
-0
lines changed Original file line number Diff line number Diff line change @@ -6,3 +6,4 @@ of these were on the playground, but I prefer to have them
6
6
in a controlled repository now.
7
7
8
8
* ` datatypes ` : examples of various datatype thingies
9
+ * ` structs.rs ` : struct and enum examples
Original file line number Diff line number Diff line change
1
+ /// Examples of structs and enums.
2
+ /// Bart Massey 2021
3
+
4
+ // Struct example.
5
+
6
+ #[ derive( Debug ) ]
7
+ struct Point {
8
+ x : u64 ,
9
+ y : u64 ,
10
+ }
11
+
12
+ impl Point {
13
+ fn x_coord ( & self ) -> u64 {
14
+ self . x
15
+ }
16
+ }
17
+
18
+ // Tuple struct example.
19
+
20
+ struct TPoint ( u64 , u64 ) ;
21
+
22
+ impl TPoint {
23
+ fn x_coord ( & self ) -> u64 {
24
+ // or "self.0"
25
+ let TPoint ( x, _) = * self ;
26
+ x
27
+ }
28
+ }
29
+
30
+ // Enum example.
31
+
32
+ pub enum Color {
33
+ Red ,
34
+ Green ,
35
+ Blue ,
36
+ Custom ( f64 , f64 , f64 ) ,
37
+ }
38
+
39
+ impl Color {
40
+ fn red ( & self ) -> f64 {
41
+ match self {
42
+ Color :: Red => 1.0 ,
43
+ Color :: Green => 0.0 ,
44
+ Color :: Blue => 0.0 ,
45
+ Color :: Custom ( r, _, _) => * r,
46
+ }
47
+ }
48
+ }
49
+
50
+ fn main ( ) {
51
+ let p = Point { x : 0 , y : 0 } ;
52
+ println ! ( "{:?}" , p) ;
53
+ println ! ( "{}" , p. x_coord( ) ) ;
54
+
55
+ let p = TPoint ( 0 , 0 ) ;
56
+ println ! ( "{}" , p. x_coord( ) ) ;
57
+
58
+ let c = Color :: Custom ( 0.5 , 0.5 , 0.0 ) ;
59
+ println ! ( "{}" , c. red( ) ) ;
60
+ }
You can’t perform that action at this time.
0 commit comments