, , . struct constructor.
, .
Rust ... , :
mod mynumber {
// The struct is public, but the fields are not.
// Note I've used a tuple struct, since this is a shallow
// wrapper around the underlying type.
// Implementing Copy since it should be freely copied,
// Clone as required by Copy, and Debug for convenience.
#[derive(Clone,Copy,Debug)]
pub struct MyNumber(i8);
impl , i8, saturating_add, , . pub fn new, Option<MyNumber>, .
impl MyNumber {
fn is_in_range(val: i8) -> bool {
val >= -100 && val <= 100
}
fn clamp(val: i8) -> i8 {
if val < -100 {
return -100;
}
if val > 100 {
return 100;
}
// Otherwise return val itself
val
}
pub fn new(val: i8) -> Option<MyNumber> {
if MyNumber::is_in_range(val) {
Some(MyNumber(val))
} else {
None
}
}
pub fn add(&self, other: MyNumber) -> MyNumber {
MyNumber(MyNumber::clamp(self.0.saturating_add(other.0)))
}
}
}
use :
use mynumber::MyNumber;
- :
fn main() {
let a1 = MyNumber::new(80).unwrap();
let a2 = MyNumber::new(70).unwrap();
println!("Sum: {:?}", a1.add(a2));
// let bad = MyNumber(123); // won't compile; accessing private field
let bad_runtime = MyNumber::new(123).unwrap(); // panics
}
, , std::ops::Add .., a1 + a2 .