如何创建Rust宏以使用其自身标识符的值定义String变量? [英] How do I create a Rust macro to define a String variable with the value of its own identifier?

查看:240
本文介绍了如何创建Rust宏以使用其自身标识符的值定义String变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个宏来定义如下内容:

I want to write a macro to define something like below:

let FOO: String = "FOO".to_string();

我可能有一个宏:

macro_rules! my_macro {
    ($name: ident, $val: expr) => {
        let $name: String = $val.to_string();
    }
}

并将其用作my_macro!(FOO, "FOO");

但是,这有点多余.我希望有类似my_macro!(FOO)的东西,它可以扩展并使用$name作为标识符,也可以在字符串值中使用.

However, this is a bit redundant. I expect to have something like my_macro!(FOO), and it can expand and use the $name as identifier, but also in the string value.

推荐答案

您要 stringify! :

macro_rules! str_var {
    ($name:ident) => {
        let $name = String::from(stringify!($name));
    };
}

fn main() {
    str_var!(foo);
    println!("foo: {:?}", foo);
}

这篇关于如何创建Rust宏以使用其自身标识符的值定义String变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆