development-programming-data-types.html


* created: 2025-05-24T12:45
* modified: 2025-06-02T08:48

title

Data types

description

These denote a piece of data (what it is).

Paint me a picture of the world.

Programming languages implement primitive data types which try to replicate a real world concept in bits and bytes. The most common ones would be:

Abstract data types

These solve the problem of representing a complex representation of the world. As shown previously, most programming languages represent a set of rudimentary concepts out of the box, but what if we wanted to represent a specific set of characters in our program, not just generic ones.

Example Username

Let's look at the example of a username, which isn't just a simple arrangement of characters, but should also follow a set of rules which we want to define. We could want our usernames to be between 3–5 characters long and only contain alphanumeric characters. Those kinds of rules can be set through an abstract data type, which could look something like this:

#[derive(Debug)]
pub struct Username(String);

#[derive(Debug)]
pub enum UsernameError {
    TooShort,
    TooLong,
    InvalidCharacters,
}

impl Username {
    pub fn new(name: &str) -> Result<Self, UsernameError> {
        if name.len() < 3 {
            return Err(UsernameError::TooShort);
        }

        if name.len() > 5 {
            return Err(UsernameError::TooLong);
        }

        if !name.chars().all(|c| c.is_alphanumeric()) {
            return Err(UsernameError::InvalidCharacters);
        }

        Ok(Username(name.to_string()))
    }
}