type) TutorialWelcome back to CodeYourCraft! Today, we're diving into the world of type aliases in Rust. Let's get started! 🎯
Type aliases are a way to give a new name to an existing type. This can make our code more readable and easier to understand. 📝
type MyType = i32; // We're giving the name `MyType` to the `i32` type
let x: MyType = 10; // Now, we can use `MyType` instead of `i32`Type aliases can help us in several ways:
Although similar, type aliases and new types (defined using struct or enum) have some differences:
Let's create a custom iterator for a linked list. We'll define a new type LinkedList, and then create a type alias LinkedListIterator to iterate over the list.
struct Node<T> {
value: T,
next: Option<Box<Node<T>>>,
}
type LinkedList<T> = Vec<Node<T>>;
type LinkedListIterator<T> = std::vec::IntoIter<Node<T>>;
fn main() {
let list: LinkedList<i32> = vec![
Box::new(Node { value: 1, next: Some(Box::new(Node { value: 2, next: Some(Box::new(Node { value: 3, next: None }))) }) })
];
let mut iterator = LinkedListIterator(list);
for item in iterator {
println!("{}", item.value);
}
}In this example, we have a Node struct that represents a node in a linked list. We then define a LinkedList as a vector of Nodes. To iterate over the list, we create a type alias LinkedListIterator for std::vec::IntoIter<Node<T>>. This allows us to iterate over the list using a for loop, just like we would with a regular iterator.
That's all for today's lesson on Type Aliases in Rust! In the next lesson, we'll explore how to create new types using struct and enum. Until then, happy coding! 🚀