Jeffrey Knight 2021-10-20 13:34:29 +01:00
rodzic 0412d4ad12
commit f630ad3fb1
1 zmienionych plików z 17 dodań i 15 usunięć

Wyświetl plik

@ -1,21 +1,18 @@
#![warn(arithmetic_overflow)]
// Rust allows another macro type: derive. It allows to "auto-implement"
// supported traits. Clone, Debug, Copy are typically handy to derive.
#[derive(Clone, Debug, Copy)]
struct MyCustomStruct {
a: i32,
b: u32,
pub c: f32
pub c: f32,
}
// A typical Rust struct has an impl block for behavior
impl MyCustomStruct {
// The new function is static function, and by convention a constructor
pub fn new(a: i32, b: u32, c: f32) -> MyCustomStruct {
MyCustomStruct {
a: a, b: b, c: c
}
MyCustomStruct { a: a, b: b, c: c }
}
// Instance functions feature a "self" reference as the first parameter
@ -25,17 +22,18 @@ impl MyCustomStruct {
}
}
#[cfg(test)]
mod tests {
use std::mem;
use super::MyCustomStruct;
use std::mem;
#[test]
fn test_custom_struct() {
// Rust features zero-overhead structs!
assert_eq!(mem::size_of::<MyCustomStruct>(),
mem::size_of::<i32>() + mem::size_of::<u32>() + mem::size_of::<f32>());
assert_eq!(
mem::size_of::<MyCustomStruct>(),
mem::size_of::<i32>() + mem::size_of::<u32>() + mem::size_of::<f32>()
);
let m = MyCustomStruct::new(1, 2, 3_f32);
assert_eq!(m.a, 1);
@ -102,6 +100,10 @@ mod tests {
// This will panic since the result is going to be an unsigned
// type which cannot handle negative numbers
// Note: _ means ignore the result
// Note: In the Rust 2021 edition, the rust compiler will catch this
// error before the runtime has a chance to panic!
// let _ = a - b;
// ^^^^^ attempt to compute `10_u32 - 11_u32`, which would overflow
let _ = a - b;
}
}