I'm currently learning rust and stumbled across a problem I'm not sure how to solve.
I want to have a type (called Guess), thats just a i32 limited to a certain number range (between 1 and 100 in example below). My current solution is to use a type alias implementing a new function to enforce the number range. Still it can be created through normal initialization, without using Guess::new(), because there are no private fields like in a struct.
Can this be prevented? Also a direct change of the value should be prevented too.
Code example (playground):
type Guess = i32;
trait G {
fn new(val: i32) -> Guess;
}
impl G for Guess {
fn new(val: i32) -> Guess {
if val < 1 || val > 100 {
panic!("Only guesses between 1 and 100 are allowed!");
}
val
}
}
fn main() {
let guess: Guess = 23; // should not be allowed
let guess: Guess = Guess::new(42); // only this should be allowed
println!("Guess this number: {}", guess);
}