#Cannot use lifetime parameters for struct

6 messages · Page 1 of 1 (latest)

quiet dagger
#

I am using wasm_bindgen to export the Universe struct to JS but the struct cannot have any lifetime parameters. Is there a way I can get around the problem of lifetime params stemming from the Edge struct?

thanks in advance

use vector3::Vector3;
use wasm_bindgen::prelude::*;

// #[wasm_bindgen]
#[derive(Clone, Debug)]
pub struct Planet {
    pub name: String,
    pub mass: f64,
    pub radius: f64,

    pub position: Vector3,
    pub velocity: Vector3,
    pub acceleration: Vector3,
}

#[wasm_bindgen]
#[derive(Debug)]
pub struct Universe<'a> {
    // width: u32,
    // height: u32,
    planets: Vec<Planet>,
    edges: Vec<Edge<'a>>,
}

impl Universe {
    fn build_edges(&mut self) {
        for i in 0..self.planets.len() {
            for j in 0..self.planets.len() {
                if i > j {
                    self.edges.push(Edge {
                        a: &self.planets[i],
                        b: &self.planets[j],
                    });
                }
            }
        }
    }
}

/// Public methods, exported to JavaScript.
#[wasm_bindgen]
impl Universe {
    pub fn tick(&mut self) {
        // ...
    }

    pub fn new() -> Universe {
        Universe {
            planets: vec![],
            edges: vec![],
        }
    }

    pub fn add_planet(&mut self, name: String, x: f64, y: f64, z: f64) {
        let planet = Planet {
            name,
            mass: 1.0,
            radius: 1.0,
            position: Vector3::new(x, y, z),
            velocity: Vector3::new(0.0, 0.0, 0.0),
            acceleration: Vector3::new(0.0, 0.0, 0.0),
        };
        self.planets.push(planet);
        self.build_edges();
    }

    pub fn render(&self) -> String {
        // self.to_string()

        format!("{:?}", self)
    }
}

#[derive(Debug)]
struct Edge<'a> {
    a: &'a Planet,
    b: &'a Planet,
}
elder garnet
#

You could use Rc/Weak for the pointers if you like, or some ID for later lookup rather than storing borrows in the Edge

quiet dagger
#

ok thank you I'll have a look

quiet dagger
#

i still need to move the planet out of the planet vector in the build_edges function to make a weak link:

impl Universe {
    fn build_edges(&mut self) {
        for i in 0..self.planets.len() {
            for j in 0..self.planets.len() {
                if i > j {
                    self.edges.push(Edge {
                        a: Rc::downgrade(&Rc::new(self.planets[i])),
                        b: Rc::downgrade(&Rc::new(self.planets[j])),
                    });
                }
            }
        }
    }
}
#

i cant move it out of the vector

elder garnet
#

You would store them as Rc inside the vector, rather than making a new Rc with that planet

So you can store a Vec<Rc<Planet>> and then you retrieve the &Rc<Planet> from the vector and downgrade that to get a Weak