Up until now, I assumed that a temporary was destructed at the end of the evaluation of the statement that had spawned it.
However, it appears that there is an exception made when using a temporary to initialize the field of a struct
.
PeterHall helpfully provided a simple code sample illustrating the difference in a comment to his answer, which I've simplified complicated a bit:
struct Wrapper<'a> {
cmd: &'a Cmd<'a>,
}
struct Cmd<'a> {
args: &'a Option<String>,
}
impl <'a> Cmd<'a> {
fn new(args: &'a Option<String>) -> Cmd<'a> {
Cmd {
args: args,
}
}
}
pub fn main() {
// OK
let cmd = Cmd {
args: &None,
};
// OK
let cmd = Wrapper {
cmd: &Cmd {
args: &None,
}
};
// Lifetime error
let cmd = Some(Cmd {
args: &None,
});
// Lifetime error
let cmd = Cmd::new(&None);
}
So, what is the exact rule for when a temporary is destructed?