Why Inline Variable is Not Dropping

Hi, I understand this code won't work because node won't live long enough and it will be dropped when scope is ended.

struct Node<'a> {
    value: u8,
    next: Option<&'a Node<'a>>,
}

fn create(previous_node: &mut Node) {
    let node = Node {
        value: 0,
        next: None,
    };

    previous_node.next = Some(&node);
}

But why this one lives ?

struct Node<'a> {
    value: u8,
    next: Option<&'a Node<'a>>,
}

fn create(previous_node: &mut Node) {
    previous_node.next = Some(&(Node {
        value: 0,
        next: None,
    }));
}
1 Like

Constant promotion.

5 Likes

The rules here are more complicated than one might like, so part of the reason for stabilizing const { ... } is that it lets you make the request for the long-lived thing more obvious.

For example, this works:

fn create(previous_node: &mut Node) {
    let node = const {
        &Node {
            value: 0,
            next: None,
        }
    };

    previous_node.next = Some(node);
}

https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=fccef134e0636a5be0993e3b53df60a2

And thus, a future edition might start requiring that in more places in order to get promotion, rather than having it be invisible even for complex things.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.