Consider adding CString literals

When writing ffi code, I found I was writing code like &CString::new("foo").unwrap() for more than one thousand times.... It would be awesome if rust has a syntax like c"foo", which automatically appends \0 to the literal, and also checks the validity(no \0 in the middle) of it at the compile time. The benefits are no runtime CString creating overhead and code simplicity. It's type is [u8].

How many code use patterns like this:

RFC issue: Consider adding CString literals · Issue #3122 · rust-lang/rfcs · GitHub

Any opinion?

This kind of post about language additions/design is better suited for


Note that there are several crates implementing C string literals using procedural macros, e.g. cstr or my own zstr. Therefore the core language doesn't need to be modified for this feature.

My zstr crate doesn't use transmute, in fact that was the whole reason I created my own macro, because I was dissatisfied with every other macro emitting transmutes right and left. My macro emits a call to a constructor function that is guaranteed to work regardless of the layout of CStr.

(The downside is that the constructor function in question is not const, so you can't yet use my macro in a const context. It would be more general and thus more appropriate to allow this constructor to become const, instead of adding a new type of literal to the language.)