I'm trying to return a static reference from a function.
When the function returns a reference with compile time data it works as expected:
fn make_web_event() -> &'static EventType {
&EventType::WebEvent(1, DomEventType::Click)
}
However, if I try to return it when it contains one of the function parameters, the compiler says that I am returning a temporary value.
fn make_web_event(id: usize, dom_event: DomEventType) -> &'static EventType {
&EventType::WebEvent(id, dom_event)
}
error[E0515]: cannot return reference to temporary value
--> src/node.rs:186:5
|
186 | &EventType::WebEvent(id, dom_event)
| ^----------------------------------
| ||
| |temporary value created here
| returns a reference to data owned by the current function
I was thinking that since the value would own the id and DomEventType, I would be allowed to do this... However, it seems like I was mistaken. Why exactly is this?
And to try and better explain my confusion, I don't understand how block A, B, and C are really any different in once it's compiled.
edit: I should have explained this better but block A and C work while block B doesn't. Rust Playground
fn main() {
// block A
{
let ev_1: &'static EventType = &EventType::WebEvent(1, DomEventType::Click);
}
// block B
{
fn make_web_event(id: usize, dom_event: DomEventType) -> &'static EventType {
&EventType::WebEvent(id, dom_event)
}
let ev_1: &'static EventType = make_web_event(1, DomEventType::Click);
}
// block C
{
fn make_static_web_event() -> &'static EventType {
&EventType::WebEvent(1, DomEventType::Click)
}
let ev_1: &'static EventType = make_static_web_event();
}
}