Welcome to our deep dive into the world of Rust! Today, we're going to explore the concepts of Sized and ?Sized types, essential building blocks in the Rust programming language. By the end of this tutorial, you'll have a solid understanding of these concepts and be able to apply them to your own projects.
<a name="intro"></a>
In Rust, every type has a size associated with it. This size is needed for memory allocation, and Rust has rules about which types can be safely allocated on the stack (Sized types) and which cannot (?Sized types). Let's delve into these types and understand their nuances.
<a name="sized"></a>
Sized types are types for which Rust can determine the exact size and layout in memory at compile time. This allows Rust to safely allocate them on the stack, making them easier to reason about and more efficient. Examples of Sized types include integers, strings, structs, enums, and tuples.
// Sized integer example
let a: i32 = 42;
// Sized string example
let b: String = String::from("Hello, World!");
// Sized struct example
struct Point {
x: i32,
y: i32,
}
let p = Point { x: 3, y: 4 };<a name="sizesized"></a>
?Sized types are types for which Rust cannot determine the exact size and layout in memory at compile time. These types can only be safely allocated on the heap, and the size of the type can change at runtime. Examples of ?Sized types include slices, trait objects, and dynamic arrays.
// ?Sized slice example
let c: &[i32] = &[1, 2, 3];
// ?Sized dynamic array example
use std::vec::Vec;
let d: Vec<i32> = Vec::new();
d.push(42);<a name="practical"></a>
Understanding the difference between Sized and ?Sized types is crucial for memory management and efficiency in Rust. When defining structs, you can mark them as Sized or ?Sized by adding the Size trait, which is automatically implemented for Sized types and needs to be implemented manually for ?Sized types.
// Sized struct example
struct Point {
x: i32,
y: i32,
}
impl Size for Point {}
// ?Sized dynamic array example
use std::vec::Vec;
impl Size for Vec<i32> {
fn size(&self) -> usize {
self.len() * std::mem::size_of::<i32>()
}
}<a name="quiz"></a>
Which of the following types is a Sized type?
That's it for our Rust tutorial on Sized and ?Sized types! As you continue your Rust journey, you'll find these concepts becoming second nature and indispensable in your code. Happy coding! 🤖💻🚀