How to access struct field through a trait object

I want access struct field through a trait object like this

trait MyTrait{}
struct MyStruct{
    val : i32,
}
impl MyTrait for MyStruct{}

fn main() {
    let obj:Box<dyn MyTrait> = Box::new(MyStruct{val : 100});
    println!("val = {}", obj.val);
}

Is there any right way to do this.

Traits do not support field access, but you can define a method for it:

trait MyTrait {
    fn get_val(&self) -> i32;
}

struct MyStruct {
    val: i32,
}
impl MyTrait for MyStruct {
    fn get_val(&self) -> i32 {
        self.val
    }
}

fn main() {
    let obj: Box<dyn MyTrait> = Box::new(MyStruct { val: 100 });
    println!("val = {}", obj.get_val());
}
3 Likes

You can also move the direct-access fields into a header struct:

struct WithHeader<T:?Sized> {
    val: i32,
    data: T
}

struct MyStruct {}

trait MyTrait {}
impl MyTrait for MyStruct {}

impl WithHeader<MyStruct> {
    // MyStruct-specific methods
}

impl<T:MyTrait + ?Sized> WithHeader<T> {
   // Methods that work for any MyTrait implementation
}

fn main() {
    let obj: Box<WithHeader<dyn MyTrait>> = Box::new(
        WithHeader {
            val:100,
            data: MyStruct
        }
    );
    println!("val = {}", obj.val);
}
2 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.