Learn how to use generics in just a few steps:
- Start off by creating a new library project with cargo new generics --lib and open the project folder in Visual Studio Code.
- 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,}
- 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> ...