Learn Generics in rust using the following simple examples.

Example 1: Simple Generics example

Learn generics using this example.

Step 1: Create Project

The first step is to create a Rust project .

Creating a Project Directory

Open a terminal and enter the following commands to make a projects directory and an inner directory for this example within that projects directory.

For Linux, macOS, and PowerShell on Windows, enter this:

$ mkdir ~/projects
$ cd ~/projects
$ mkdir your_example_name
$ cd your_example_name

For Windows CMD, enter this:

> mkdir "%USERPROFILE%\projects"
> cd /d "%USERPROFILE%\projects"
> mkdir your_example_name
> cd your_example_name

Step 2: Dependencies

No dependencies are needed for this project.

Step 3: Write Code

Create a main.rs file and add the following code:

main.rs

fn map<T, U, F>(vector: &[T], function: F) -> Vec<U>
    where F: for<'a> Fn(&'a T) -> U {
    let mut accumulator : Vec<U> = Vec::new();
    for element in vector.iter() {
        accumulator.push(function(element));
    }
    return accumulator;
}
fn main() {
    let strings = ["a", "b", "c"];
    let new_strings = map(&strings, |&x| {let mut msg = String::from(x); msg.push_str(x); msg});
    println!("{:?} -> {:?}", strings, new_strings);
}

Result

If you run the code you will get the following:

["a", "b", "c"] -> ["aa", "bb", "cc"]

Run

Save the code and run your code as follows:

Assuming our file name is main.rs, first compile it

$ rustc main.rs

then run it:

$ ./main

On Windows, enter the command .\main.exe instead of ./main:

compile:

> rustc main.rs

then run it:

> .\main.exe