#String literals in macros

13 messages · Page 1 of 1 (latest)

glad slate
#

Say I have code like this:

#[deprecated = "string"]
fn foo() {}

but I want "string" to be defined once and re-used in many places. So far the only way I've found is to define a macro:

macro_rules! my_string { () => { "string" } };

#[deprecated = my_string!()]
fn foo() {}

but it seems as if there should be a simpler way. Can I somehow directly use a string literal in an attribute like that?

worldly osprey
#

As any item you could define, other than a macro, could only be evaluated by the macro as an expression, I'm pretty sure a is the only option in this case...

glad slate
#

ok, thanks!

reef creek
#

but this happens a lot later than macro expansion

#

so it won't work in the case you are working with

worldly osprey
#

const values can be derived from an expression though, so I'd presume it doesn't insert the full expression, just its result...

reef creek
#

this is the reason there is a clippy lint for const M = Mutex::new(...). if you did that, every call to the mutex would create a new one, making it useless

#

you need static M = Mutex::new(...)

worldly osprey
#

Which in the case of an &str constant, it'd produce an &'static str, rather than a string literal...

reef creek
reef creek
hardy iron
# glad slate Say I have code like this: ```rust #[deprecated = "string"] fn foo() {} ``` bu...

Alas, this is kind of the best you can do.
An option if you are deprecating a bunch if things with the same error message could be to define an attribute_alias! using https://docs.rs/macro_rules_attribute (but I wouldn't pull a dependency just for this):

attribute_alias! {
    #[apply(deprecated_foo_api)] = #[deprecated = "The API foo is deprecated; use bar instead"]
}

so as to:

#[apply(deprecated_foo_api)]
fn foo() {}