NutellaFan
NutellaFan

Reputation: 85

Accessing a field in generic structure

Given this struct:

pub struct A {
    pub C: B,
}

I'm looking create Rust container with elements of A, and access A.C in that generic Rust container. Here is such a container:

pub struct MyArray<A, C> {
    data: Vec<A>,
    size: usize,
}

impl<A, C> MyArray {
    // Access the value in the ith element of data
    pub fn get_value(self, i: u64) -> u64 {
        self.data[i].C
    }
}

Given the following struct:

pub struct House {
    pub num_rooms: u64, 
} 

I want to instantiate a generic types like this:

let h: MyArray<House, num_rooms> = MyArray(6);

let d: MyArray<Cat, num_lives> = MyArray(10);

Then I want do be able to call h.func(5) to get the value of specified field in the 6th element of the Rust container.

I'm not sure if this is possible at all. If it is, macros / generics are probably needed.

Upvotes: 0

Views: 1077

Answers (1)

Sven Marnach
Sven Marnach

Reputation: 601809

You can store a getter function for the field you want to access alongside your container, e.g.

pub struct MyVec<A, G> {
    data: Vec<A>,
    getter: G,
}

impl<A, G, T> MyVec<A, G>
where
    G: Fn(&A) -> T,
{
    pub fn get_value(&self, i: usize) -> T {
        (self.getter)(&self.data[i])
    }
}

struct Wobble {
    gloink: u64,
}

impl Wobble {
    fn gloink(&self) -> u64 {
        self.gloink
    }
}

fn main() {
    let v = MyVec {
        data: vec![Wobble { gloink: 42 }],
        getter: Wobble::gloink,
    };
    println!("{}", v.get_value(0));
}

Playground

Upvotes: 3

Related Questions