问题描述
Rust具有 stringify!
宏以获取表达式作为字符串.有没有办法获得输出字节的等效功能?
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?
就像表达式被写为字节字符串文字一样,例如:b"some text"
.
As if the expression were written as a byte string literal, e.g.: b"some text"
.
使用宏而不是str.as_bytes()
的原因是不能使用转换函数来构造const
值.查看此内容您可能为什么要使用此宏的问题.
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.
推荐答案
如果您使用每晚的Rust(自1.28.0-nightly,2018-05-23开始),则可以启用const_str_as_bytes
功能,该功能会将进入const
函数.
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]
}
(演示)
这篇关于是否有一个等效于'stringify'宏的字节?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!