Using `concatcp` for const fn parameters?

Is it possible to use concatcp (or a similar macro or function) for const fn parameters such as raw_name below? Or is such functionality only possible via macros?

use const_format::concatcp;
pub const SECONDARY_KEY_PREFIX: &str = "_";
pub const fn skey(raw_name: &str) -> &str {
    concatcp!(SECONDARY_KEY_PREFIX, raw_name)
}

With the previous code, I’m getting this error:

error[E0080]: evaluation of constant value failed
 --> src/token.rs:4:5
  |
4 |     concatcp!(SECONDARY_KEY_PREFIX, raw_name)
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ referenced constant has errors
  |
  = note: this error originates in the macro `$crate::pmr::__concatcp_impl` which comes from the expansion of the macro `concatcp` (in Nightly builds, run with -Z macro-backtrace for more info)

What’s concatp?

Constant functions are, well, functions. They can be called as ordinary, with runtime-defined parameters. The only difference is that, if they're called with compile-time constants, then they will yield a compile-time constant.

concatcp, on the other hand, is a macro. And macros are purely compile-time things - they can not use runtime-defined values in any way. Therefore, they can't use the const fn argument.

Try to use associated constants instead

1 Like

Thanks! So my options for implementing and using skey() are: a macro or lazy_static with non-const code? Others?

Why can’t you just replace your usual argument with a generic one? Like this (untested, not the best unstable code):

#![feature(adt_const_params)]

pub const fn skey<const RAW: &'static str>() -> &str {
    concatcp!(SECONDARY_KEY_PREFIX, RAW)
}

Or are you trying to fit into stable?

Well, I’m a beginner, so my knowledge is limited.

Thanks for your suggestion! Alas, it doesn’t seem to work.