Copy & Clone Triats
- Both are used for duplicating the values.
- All types that implement Copy must also implement Clone, but the reverse is not true
Copy (Shallow Copy) | Clone (Deep Copy) | |
---|---|---|
What | Type implementing(copy triat) can be duplicated simply by Bitwise Copying | For types that require more complex duplication logic. |
Efficient | More efficient since it involves a simple bitwise copy | May involve more complex operations and potentially higher overhead |
Used for | Simple scalar types(Eg: int, struct containing simple types) | For complex datatypes which manage resources on heap(like String, Vec, etc) |
Example |
|
|
Default trait
- Used to give default value
#[derive(Default)] | Default value by user |
---|---|
Rust to provide Default implementation
|
User overrides the default() function provided by Default Trait
|
drop trait
-
Custom code within the destructor.
When a value is no longer needed, Rust runs a “destructor” on that value, but if we want to perform some task in destructor, use drop trait.
#[derive(Default)]
pub struct S {
x : i32,
}
impl Drop for S {
fn drop(&mut self){
println!("Dropping");
}
}
fn main() {
{
let s:S = Default::default();
println!("{}", s.x);
}
println!("After scope");
}
$ cargo run
0
Dropping
After scope
future trait
-
future is a "asynchronous value" that may not have finished computing yet.
Thread waits on future to become available. These are similar to epoll(), not smilar to poll() or select().
use std::pin::Pin;
use std::task::Context;
pub trait Future {
type Output;
fn poll(self: Pin <&mut Self>, cx: &mut Context <'_>) -> Poll <Self::Output>;
}
pub enum Poll <T> {
Ready(T),
Pending,
}
Iterator trait
-
Used for processing sequences of data, allowing you to traverse or consume elements one by one.
With Iterators only Rust handles collections, streams of data, and other sequential operations.
pub trait Iterator {
type Item; // The type of the elements being iterated over.
// The Iterator trait requires one method to be implemented
// This method advances the iterator and returns the next item in the sequence wrapped in Option
fn next(&mut self) -> Option;
}
Send, Sync trait
Send | Sync | |
---|---|---|
What | Types (T) that can be transferred across thread boundaries. | Types for which it is safe to share references (&T) between threads. |
unsafe trait | Yes | Yes |
Automatically derived trait |
Yes if type is thread-safe, then it Automatically derived Send,sync Apart from Rc and UnsafeCell, all types are Send, Sync. |
Yes |
Can be implemented |
Yes
|
Yes
|
Can be unimplemented |
Yes
|
Yes
|