是否有一个等效于'stringify'宏的字节? [英] Is there a byte equivalent of the 'stringify' macro?

查看:87
本文介绍了是否有一个等效于'stringify'宏的字节?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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'宏的字节?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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