0

this question is probably trivial but I haven't found any good documentation about temporary values in rust yet:

Why is no temporary value created when directly returning a reference to a newly constructed struct in contrast to creating the struct with new()? AFAIK both functions do the same by creating and returning a reference to a newly created struct instance.

struct Dummy {}

impl Dummy {
    fn new() -> Self {
        Dummy {}
    }
}

// why does this work and why won't there be a temporary value?
fn dummy_ref<'a>() -> &'a Dummy {
    &Dummy {}
}

// why will there be a temp val in this case?
fn dummy_ref_with_new<'a>() -> &'a Dummy {
    &Dummy::new() // <- this fails
}
fluxus
  • 1

1 Answers1

0

Dummy {} is constant, so it can have static lifetime. If you tried to return a mutable reference to it, or if the result weren’t constant, it wouldn’t work.

struct Dummy {
    foo: u32,
}

// nope
fn dummy_ref<'a>(foo: u32) -> &'a Dummy {
    &Dummy { foo }
}
Ry-
  • 218,210
  • 55
  • 464
  • 476