Implicit conversion from Arc<ConcreteType> to Arc<dyn Trait>

How this code works in (1):

use std::sync::Arc;

trait MyTrait {
    fn f(&self) -> usize;
impl MyTrait for String { fn f(&self) -> usize { self.len() } }

fn f(value: Arc<dyn MyTrait>) {}
fn main() {
    let p: Arc<String> = Arc::new("aaa".to_string());


The initial p is smart pointer to String structure, while Arc<dyn MyTrait> is smart pointer to String plus pointer to vtable. So how implicit conversion from Arc<String> -> Arc<dyn MyTrait> works, where pointer to vtable stored?

It's right next to the pointer to the data. Arc<dyn Trait> (and generally, all pointer-like types to all dynamically-sized types) are wide pointers, with metadata (vtable or length information) stored along with the "real" pointer.

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.