Skip to content

Borrowing static array that contains another static array represented by literal doesn't work when expressed inline #54224

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

Closed
pepyakin opened this issue Sep 14, 2018 · 4 comments

Comments

@pepyakin
Copy link
Contributor

Why does this work:

use std::borrow::Cow;

pub const X: [u8; 3] = *b"ABC";
pub const Y: Cow<'static, [ [u8; 3] ]> = Cow::Borrowed(&[X]);

but this doesn't?

use std::borrow::Cow;

pub const Z: Cow<'static, [ [u8; 3] ]> = Cow::Borrowed(&[*b"ABC"]);
@Havvy
Copy link
Contributor

Havvy commented Sep 15, 2018

error[E0597]: borrowed value does not live long enough
 --> src/lib.rs:3:57
  |
3 | pub const Z: Cow<'static, [ [u8; 3] ]> = Cow::Borrowed(&[*b"ABC"]);
  |                                                         ^^^^^^^^^- temporary value only lives until here
  |                                                         |
  |                                                         temporary value does not live long enough
  |
  = note: borrowed value must be valid for the static lifetime...

@memoryruins
Copy link
Contributor

memoryruins commented Sep 15, 2018

If we add #![feature(nll)], it compiles. (playground)

It appears related to the issue described in #43058, which was fixed by nll.
cc @rust-lang/wg-compiler-nll

@memoryruins memoryruins added the A-NLL Area: Non-lexical lifetimes (NLL) label Sep 15, 2018
@pnkfelix pnkfelix added the fixed-by-NLL Bugs fixed, but only when NLL is enabled. label Sep 19, 2018
@nikomatsakis
Copy link
Contributor

This is a bit curious. I'm digging in a bit more.

@eddyb eddyb removed fixed-by-NLL Bugs fixed, but only when NLL is enabled. A-NLL Area: Non-lexical lifetimes (NLL) labels Sep 19, 2018
@eddyb
Copy link
Member

eddyb commented Sep 19, 2018

It's a bug that NLL "fixes" this - see #51990 (comment).

@pepyakin This is not a bug (ignoring NLL), but we need to document it better.

*b"ABC" is not considered a "promotable-to-'static constant expression". We rely on evaluating it later to ensure that it is valid where written, but it's not treated as promotable because we don't track references/pointers in the promotion analysis, and promotion could change behavior.

We could maybe relax the rules a bit here, since we're in a constant anyway, and promotion rules require not involving named variables, but we'd need to be careful around Drop and unsafe code.

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

6 participants