Is there a byte equivalent of the 'stringify&#

2019-06-20 06:50发布

Rust has a stringify! macro to get an expression as a string. Is there a way to get the equivalent functionality that outputs bytes instead?

As if the expression were written as a byte string literal, eg: b"some text".


The reason to use a macro instead of str.as_bytes() is that conversion functions cant be used to construct const values.
See: How to construct const integers from literal byte expressions?
for why you might want to use this macro.

标签: macros rust
1条回答
smile是对你的礼貌
2楼-- · 2019-06-20 07:15

If you are using nightly Rust (since 1.28.0-nightly, 2018-05-23), you may enable the const_str_as_bytes feature which turns as_bytes() into a const function.

#![feature(const_str_as_bytes)]

fn main() {
    const AAA: &[u8] = stringify!(aaa).as_bytes();
    println!("{:?}", AAA);  // [97, 97, 97]
}

(Demo)

查看更多
登录 后发表回答