Generic Types, Traits, and Lifetimes

In this chapter, we'll explore write flexible, reusable code with generics, traits, and lifetimes.

Generic Types, Traits, and Lifetimes

Every programming language has tools for effectively handling duplication of concepts. In Mana, one such tool is generics: abstract stand-ins for concrete types or other properties.

This chapter covers:

Removing Duplication

Consider finding the largest number:

fn largest_int(list: Vec<int>) -> int {
    let mut largest = list[0]
    for item in list {
        if item > largest {
            largest = item
        }
    }
    return largest
}
 
fn largest_char(list: Vec<char>) -> char {
    let mut largest = list[0]
    for item in list {
        if item > largest {
            largest = item
        }
    }
    return largest
}

These functions are identical except for the type. Generics eliminate this duplication.

Let's start with Generic Data Types.