Help with creating a new type the idiomatic rust way

Hello,

I am a beginner learning Rust. I have created this newtype:

// Create the ValidationCode newtype
#[derive(Debug, Serialize, Deserialize, sqlx::Type)]
pub struct ValidationCode(i64);

impl ValidationCode {
    pub fn new() -> i64 {
        rand::random_range(10000..=99999)
    }
}

// Convert from ValidationCode to i64
impl From<ValidationCode> for i64 {
    fn from(validation_code: ValidationCode) -> Self {
        validation_code.0
    }
}

Then, when I use this type like this:

// Generate validation code
let validation_code: i64 = ValidationCode::new();

The i64 part is inserted by vscode using the rust-analyzer plugin.

Although it works I wonder why vscode inserts :i64?
I was expecting : ValidationCode

as that is the type, right?

Thank you for any help or insights

Because ValidationCode::new returns i64 - you literally defined it as such.

Then you should create it explicitly:

impl ValidationCode {
    pub fn new() -> Self {
        Self(rand::random_range(10000..=99999))
    }
}
3 Likes

Perfect! Thanks. A new set of eyes always helps. I changed it to:

new inside impl ValidationCode is like a usual function. If you write that its result type is i64, ValidationCode::new() is of type i64. No special handling here.

Of course, inside impl ValidationCode, Self is the same as ValidationCode.