Hello everyone, so while writing a toy ray tracer, I have run into yet another problem. The snippet below gives an error, saying input_meshes
is moved out?, which is then passed as the member of a SceneConfig
struct.
My best guess as to why this happening is because I am using a "temporary" object inside a for loop to assign a reference to a struct that obviously outlives the temporary object. What I want to accomplish is that the meshes
array will be owned by the SceneConfig
struct in question, and I want to somehow assign a reference/pointer to some element inside the meshes
vector into a Triangle
object. So while Rust is right in the sense that I am trying to assign a reference to a temporary object, I am not sure how I should handle this usecase in an idiomatic way. Any suggestions and help would be appreciated!
src/lib.rs:
pub struct SceneConfig<'a> {
pub geometries: Vec<Arc<Hitable + 'a>>,
pub meshes: Vec<TriangleMesh>,
}
...
impl<'b> SceneConfig<'b> {
pub fn parse_args_and_construct_scene(args: &[String]) -> Result<SceneConfig, Box<dyn Error>> {
//Geometry
let mut geometries: Vec<Arc<Hitable>> = vec![];
let mut meshes: Vec<TriangleMesh> = vec![];
for i in 0..10 {
let type_of_geometry = "mesh";
match type_of_geometry {
"mesh" => {
let mut input_meshes : Vec<TriangleMesh> = TriangleMesh::new(mesh_absolute_path);
meshes.append(&mut input_meshes);
for input_mesh in input_meshes.into_iter() {
let triangles: Vec<Triangle> = input_mesh.get_triangles_from_mesh();
for triangle in triangles {
geometries.push(Arc::new(triangle));
}
}
}
_ => {
}
}
}
Ok( geometries: geometries,
meshes: meshes,)
}
src/geometry/triangle.rs:
#[derive(Clone)]
pub struct TriangleMesh {
//Same as tobj::Mesh
pub positions: Vec<f32>,
pub normals: Vec<f32>,
pub texcoords: Vec<f32>,
pub indices: Vec<u32>,
pub material_id: Option<usize>,
}
pub struct Triangle<'a> {
indices: Vec<u128>,
mesh: &'a TriangleMesh,
}
EDIT: Here's the compiler error:
error[E0515]: cannot return value referencing local variable `input_mesh`
--> src\lib.rs:164:9
|
137 | let triangles: Vec<Triangle> = input_mesh.get_triangles_from_mesh();
| ---------- `input_mesh` is borrowed here
...
164 | / Ok(SceneConfig {
165 | | scene_file_name: scene_filename,
166 | | out_file: out_file,
167 | | film: film,
... |
170 | | meshes: meshes,
171 | | })
| |__________^ returns a value referencing data owned by the current function
error: aborting due to previous error
For more information about this error, try `rustc --explain E0515`.