Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

macros

rust

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.

like image 292
ideasman42 Avatar asked Feb 13 '17 08:02

ideasman42


People also ask

What is stringification?

stringification (uncountable) (computing) The act or process of stringifying; conversion to a string.

How to stringify in C?

Stringification in C involves more than putting doublequote characters around the fragment; it is necessary to put backslashes in front of all doublequote characters, and all backslashes in string and character constants, in order to get a valid C string constant with the proper contents.


1 Answers

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)

like image 100
kennytm Avatar answered Dec 30 '22 16:12

kennytm