Hello! I'm still very new and trying to learn the right way to do things without just cloning
my way out of a problem
Suppose I have some structs struct:
struct Data {
pub x: i32,
pub y: i32,
}
struct Agent {
q: i32,
r: i32,
}
impl Agent {
pub fn get_data(&self) -> Data {
Data { x: self.q, y: self.r }
}
Now, suppose I have a method where someone can optionally send alternative Data
:
fn do_stuff(agent: &Agent, data: Option<&Data>) {
let our_data: &Data;
if data.is_none() {
our_data = &agent.get_data();
} else {
our_data = data.unwrap();
}
do_other_things(our_data);
[...]
}
This doesn't work because &robot.get_data()
creates a temporary value that goes out of scope. I know that one way I can fix this is to have the do_stuff
function just taken an Option<Data>
but then it seems like the called would need to call it with cloned Data
since it can't just send a reference.
So how would people solve this problem?