-
Notifications
You must be signed in to change notification settings - Fork 13k
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
Static lifetime deduced for constant, but not for return values of const fn #90370
Comments
This seems to be intended behaviour, see rust-lang/const-eval#19, RFC 3027 and the const-eval documentation on promotion |
The #![allow(incomplete_features)]
#![feature(inline_const)]
const fn inc(n: u32) -> u32 {
n + 1
}
fn assert_static(_r: &'static u32) {}
fn main() {
assert_static(&1);
assert_static(&const { inc(1) });
} |
Indeed, this is expected behavior -- promoting So I will close this issue; the intended convenient way to write such code in the future is via inline consts, tracked at #76001. |
Oh, also, a shameless plug: I have a little crate that partially implements inline consts as a macro -- https://crates.io/crates/inline-const. |
In rust borrowed constants have static lifetimes, even if the constants are simple literals in the middle of a function. For example, this compiles:
This works even in more involved situations, such as when the "literal" is a macro-generated array of structs whose fields are literals. (That's my actual use case, but I'll refer to the simple case of just having a
u32
for simplicity.)The problem is that it no longer works if the value is returned by a
const fn
:Playground
I would expect (or rather wish) for the latter code to compile since the former did. Note that, since
const
andstatic
arestatic
, it is possible to work around it by creating an explicitconst
orstatic
inbetween. For example, all of these compile:Playground
While a workaround is available, it is not always obvious. Also it would be much nicer not to have to introduce all the temporary constants/statics, especially in code that calls several different const fns.
The text was updated successfully, but these errors were encountered: