Convert Arc<Foo> to Arc<Bar> if Bar is a newtype wrapper of Foo

I would like to convert Arc<Foo> to Arc<Bar> where Bar is a newtype wrapper of Foo:

#[repr(transparent)]
struct Bar(Foo)

Is there any crate can achieve it?

I found ref-cast can convert &Foo to &Bar, so I guess it's possible to convert Arc<Foo> to Arc<Bar>

It looks like bytemuck has a function for this.

#[derive(bytemuck::TransparentWrapper)]
#[repr(transparent)]
struct Bar(Foo);

pub fn convert(foo: Arc<Foo>) -> Arc<Bar> {
    bytemuck::allocation::TransparentWrapperAlloc::wrap_arc(foo)
}
3 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.