How to do it...

Learn how to use generics in just a few steps:

  1. Start off by creating a new library project with cargo new generics --lib and open the project folder in Visual Studio Code.
  2. A dynamic array is a data structure many of you will use every day. In Rust, the implementation is called Vec<T>, while other languages know it as ArrayList or List. First, let's establish the basic structure:
use std::boxed::Box;use std::cmp;use std::ops::Index;const MIN_SIZE: usize = 10;type Node<T> = Option<T>;pub struct DynamicArray<T>where    T: Sized + Clone,{    buf: Box<[Node<T>]>,    cap: usize,    pub length: usize,}
  1. As the struct definition shows, the main element is a box of type T, a generic type. Let's see what the implementation looks like:
impl<T> ...

Get Rust Programming Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.