Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

References/borrows of const values don't have 'static lifetime #40522

Closed
mzji opened this issue Mar 14, 2017 · 4 comments
Closed

References/borrows of const values don't have 'static lifetime #40522

mzji opened this issue Mar 14, 2017 · 4 comments

Comments

@mzji
Copy link

mzji commented Mar 14, 2017

Example:

const FOO: usize = 0;

fn bar() -> &'static usize {
    &FOO
}

fn main() {
    bar();
}

Get error:

rustc 1.17.0-nightly (b1e31766d 2017-03-03)
error: borrowed value does not live long enough
 --> <anon>:5:6
  |
5 |     &FOO
  |      ^^^ does not live long enough
6 | }
  | - temporary value only lives until here
  |
  = note: borrowed value must be valid for the static lifetime...

error: aborting due to previous error
@codyps
Copy link
Contributor

codyps commented Mar 14, 2017

This is expected. From the signature of bar(), we can't know that FOO will have been borrowed afterwards.

Borrows will generally be scoped by their inner-most block (like the function body).

You can, however, do this:

const FOO_: usize = 0;
const FOO: &'static usize = &FOO_;

fn bar() -> &'static usize {
    FOO
}

fn main() {
    bar();
}

Edit: that said, it does seem like this could be made to work. We don't really need to know that FOO has been borrowed because we can't borrow it mutably, we can't assign to it, and we won't drop it.

@mzji
Copy link
Author

mzji commented Mar 14, 2017

@jmesmon Thanks for the solution! Actually I just solve my problem with this pattern. However I have a question: could we do inference here to give the reference a 'static lifetime?

@Stebalien
Copy link
Contributor

Stebalien commented Mar 14, 2017

The problem here is static promotion. You can fix this by using static, instead of const:

static FOO: usize = 0;

fn bar() -> &'static usize {
    &FOO
}

fn main() {
    bar();
}

Basically, constants are compile-time only so &FOO gets evaluated to &0 (where 0 is a temporary) at compile-time.

Note: The linked RFC has not been implemented (which is why this doesn't currently work).

@mzji
Copy link
Author

mzji commented Mar 14, 2017

After reading the book, I think I know the point showed by @Stebalien 's code. Thank you all!

@mzji mzji closed this as completed Mar 14, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants