Is there a byte equivalent of the 'stringify' macro?

对着背影说爱祢 提交于 2019-12-23 09:35:06

问题


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, e.g.: b"some text".


The reason to use a macro instead of str.as_bytes() is that conversion functions can't be used to construct const values.See this question for why you might want to use this macro.


回答1:


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)



来源:https://stackoverflow.com/questions/42199312/is-there-a-byte-equivalent-of-the-stringify-macro

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!