1
-
1
+ #! [ warn ( arithmetic_overflow ) ]
2
2
// Rust allows another macro type: derive. It allows to "auto-implement"
3
3
// supported traits. Clone, Debug, Copy are typically handy to derive.
4
4
#[ derive( Clone , Debug , Copy ) ]
5
5
struct MyCustomStruct {
6
6
a : i32 ,
7
7
b : u32 ,
8
- pub c : f32
8
+ pub c : f32 ,
9
9
}
10
10
11
11
// A typical Rust struct has an impl block for behavior
12
12
impl MyCustomStruct {
13
-
14
13
// The new function is static function, and by convention a constructor
15
14
pub fn new ( a : i32 , b : u32 , c : f32 ) -> MyCustomStruct {
16
- MyCustomStruct {
17
- a : a, b : b, c : c
18
- }
15
+ MyCustomStruct { a : a, b : b, c : c }
19
16
}
20
17
21
18
// Instance functions feature a "self" reference as the first parameter
@@ -25,17 +22,18 @@ impl MyCustomStruct {
25
22
}
26
23
}
27
24
28
-
29
25
#[ cfg( test) ]
30
26
mod tests {
31
- use std:: mem;
32
27
use super :: MyCustomStruct ;
28
+ use std:: mem;
33
29
34
30
#[ test]
35
31
fn test_custom_struct ( ) {
36
32
// Rust features zero-overhead structs!
37
- assert_eq ! ( mem:: size_of:: <MyCustomStruct >( ) ,
38
- mem:: size_of:: <i32 >( ) + mem:: size_of:: <u32 >( ) + mem:: size_of:: <f32 >( ) ) ;
33
+ assert_eq ! (
34
+ mem:: size_of:: <MyCustomStruct >( ) ,
35
+ mem:: size_of:: <i32 >( ) + mem:: size_of:: <u32 >( ) + mem:: size_of:: <f32 >( )
36
+ ) ;
39
37
40
38
let m = MyCustomStruct :: new ( 1 , 2 , 3_f32 ) ;
41
39
assert_eq ! ( m. a, 1 ) ;
@@ -49,12 +47,12 @@ mod tests {
49
47
let m2 = m. clone ( ) ;
50
48
// We use the Debug formatter to format the struct
51
49
assert_eq ! ( format!( "{:?}" , m2) , "MyCustomStruct { a: 1, b: 2, c: 3.0 }" ) ;
52
-
50
+
53
51
// This is an implicit (deep) copy, possible only with the Copy trait
54
52
// Added mutability allows to change struct members
55
53
let mut m3 = m;
56
-
57
- // As a copy, this should not affect the other instances
54
+
55
+ // As a copy, this should not affect the other instances
58
56
m3. a = 100 ;
59
57
60
58
// We'll make sure that the values didn't change anywhere else
@@ -87,7 +85,7 @@ mod tests {
87
85
assert_eq ! ( a. overflowing_sub( b) , ( 18446744073709551584 , true ) ) ;
88
86
89
87
// By default, Rust variables are immutable, add the mut qualifier
90
- // to be able to change the value
88
+ // to be able to change the value
91
89
let mut c = 100 ;
92
90
c += 1 ;
93
91
assert_eq ! ( c, 101 ) ;
@@ -102,6 +100,10 @@ mod tests {
102
100
// This will panic since the result is going to be an unsigned
103
101
// type which cannot handle negative numbers
104
102
// Note: _ means ignore the result
105
- let _ = a - b;
103
+ // Note: In the Rust 2021 edition, the rust compiler will catch this
104
+ // error before the runtime has a chance to panic!
105
+ // let _ = a - b;
106
+ // ^^^^^ attempt to compute `10_u32 - 11_u32`, which would overflow
107
+ let _ = a - b;
106
108
}
107
109
}
0 commit comments