What are types?

Types in programming languages are different across the board. Essentially the only common denominator is primitive types. These are types that are not implemented with the language and exist as a consequence of the languages features but rather they are a part of the language. Some common types include:

  • integers
  • characters
  • strings
  • booleans
  • floats

This list is going to be different for every language but it works in general.

The other side of primitive types is compound types. These mainly exist as sort-of extensions to the main types. Here the list is a bit smaller:

  • struct/class
  • pointer
  • list/array
  • (union1)

Types in rust

In rust there are a few primitive types:

  • integer
  • character
  • slice/array
  • boolean
  • floats

These types can then be compounded using structs and enums.

Traits

Rusts main superpower comes in the form of polymorphisms. In contrast to object oriented languages it is based on traits. These traits (similar to interfaces in C++) work by defining common capabilities every implementer will have.

trait Widget {
    fn draw();
}

struct Button {
    // ...
}

impl Button {
    // ...
}

impl Widget for Button {
    fn draw() {
        // ...
    }
}

Here we are defining a trait Widget that tells each implementer to have a function draw with that exact signature. Now we could have a function like this:

fn draw_all<T>(widgets: &[T])
    where T: Widget 
{
        // ...
}

We define the function using type generics. An argument of a slice over the generic type T is passed as an argument. The generic type is restricted using the bound T: Widget which means T has to implement Widget. You can also provide multiple restrictions:

fn draw_all<T>(widgets: &[T])
    where T: Widget + Send
{
        // ...
}

Notable here is the very mathematical definition of the function. If I had to read this out loud I would do it as follows:

the function draw_all with an argument of a slice over T returning nothing where T implements Widget

Which is very close to how you would deal with similar things on a purely mathematical basis

A closer look at generics

The syntax with T that we used above is called “generics” in rust. This is because you define a function in a type-generic way, although you can restrict the type itself using trait bounds.

These trait bounds just define which traits a type has to implement in order for this function to apply. An example here I talked about in another article is the Result type:

pub enum Result<T, E> {
    Ok(T),
    Err(E),
}

Here you have a generic type with two types that can be chosen freely as no further bound is included.

But it goes even further. Let’s take a look at the From trait:

pub trait From<T>: Sized {
    fn from(value: T) -> Self;
}

The From trait is used for infallible conversions where you construct a new object from an existing one. The closely-related Into trait does the same but turns an existing object into one of a different type. If you have ever read through the documentation you might know that From implements Into as well. How does this work? Well, the answer is generics. Let’s look at the implementation of this feature:

impl<T, U> Into<U> for T
where
    U: From<T>,
{
    // ...
    fn into(self) -> U {
        U::from(self)
    }
}

This implementation works by defining a generic implementation which implements the Into trait on any type that supports the From trait. This means, if you have a type T that implements From<String>, the type String will implement Into<T> even though you would normally not be able to implement this after the fact on String.

Other important traits

Iterator

The Iterator trait is exactly what it says it is. It is the trait that powers all iterators in rust. When implementing you only need to define one type and a single method: the Item type and the next method. If you need to define a custom iterator for whatever reason use this trait.

FromIterator

This trait is the one that powers the .collect() method on iterators. At least, that is its most common use case as far as I’m concerned. One more extreme implementation is the following:

impl<A, E, V: FromIterator<A>> FromIterator<Result<A, E>> for Result<V, E>

This implementation allows an Iterator over Results to be turned into a single Result which holds a vector in its Ok variant. This can make it more comfortable to use map and filter and the like if you have to deal with results.

Display

This is probably one of the easier traits to understand. It has a single important method .fmt() which is used to format a type into some formatter. The Display trait is used for the .to_string() method for example and allows your type to be used in format strings passed to println!() and format!().

Closing thoughts

A good type system can sometimes be the difference between a good and a bad language. Although not very important to most people, I think it should be valued way more than it currently is. Rusts type system is just too good to pass up. Similar systems in e.g. Haskell are also incredibly good.

To me personally rusts type system is amazing and it offers a bunch of great mechanics for writing clean and incredibly easy to understand code. Together with the broader rust ecosystem this makes for an amazing language and developer experience.


  1. While important in C, unions are often not important in other languages ↩︎