r/rust•
socratesTwo

Why does concat! demand literals?

Does anyone know why the following doesn't build?

const GREETING: &'static str = "Hello";
const PLACE: &'static str = "World";
const DOESNT_BUILD: &'static str = concat!(GREETING, ", ", PLACE);

I mean, yes, it's because concat only works for literals, but why should that be the case?

Posted Feb 21, 2020, 11:44 PM UTC

1012
usernamedottxt•

https://github.com/Vurich/const-concat/blob/master/README.md

Here’s is a great write up and shows how terrible the work around is.

13
protestor•

Well const_concat! seems like a great macro. Can the hack result in UB somehow?

6
stumpychubbins•

Author here, I saw this post and was immediately like my time has come, I'm happy to see that someone beat me to it

1
GoldsteinQ•

Because it's a macro, so it knows nothing about constant values.

8
socratesTwoOP•

Care to elaborate?

3
GoldsteinQ•

Macro gets only constant names, without values.

7
socratesTwoOP•

Ah. And is that only macros by example, or would proc macros be incapable of this as well?

3
etareduce•

All macros work on syntax. Conceptually, the input of a macro is a stream of tokens (and tokens are things like identifiers, ;, string literals, and so on). This happens before there even is a type system, so to the macro system, all it knows is that you've passed in an identifier GREETING, but not what is behind it. This is irrespective of whether the macro is declarative or procedural.

12