I'm just learning Rust and run into an interesting phenomenon using Arc
. With Arc
, let's say I wrap a vec
with arc
, I can access that vec
just as it was a normal vec
without changing my code. For example:
let arc = Arc::new(vec![0,1,2,3]);
for x in arc.iter() {
print!("{}", x);
}
// I can even call `len` as if it was a normal vector
println!("{}", arc.len());
I have some custom code which I am wrapping a vector and adding some custom logic on top of it.
struct Wrapper {
underlying: Vec<i32>,
my_custom_field_for_custom_logic: bool
}
// my wrapper
let wrap = Wrapper {
underlying: vec![0,1,2,3],
my_custom_field_for_custom_logic: true
};
for x in wrap.underlying.iter() {
println!("{}", x);
}
For my structure, I have to use a special field called underlying
to access the underlying vector.
I looked into Arc
's source code and found this:
pub struct Arc<T: ?Sized> {
ptr: NonNull<ArcInner<T>>,
phantom: PhantomData<ArcInner<T>>,
}
Essentially it has fields for underlying data as well. I'm new to rust, so the rest of the code goes way over my head.
So my question is essentially how can I make my Wrapper
structure behave like Arc
, in the sense that I can directly call vector methods (or methods of the underlying data) without accessing a special field.
Not a big deal, but I would like to know how it's done.