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: https://github.com/search?q=cstring%3A%3Anew+unwrap&type=code

RFC issue: https://github.com/rust-lang/rfcs/issues/3122

Any opinion?

This kind of post about language additions/design is better suited for https://internals.rust-lang.org/

Thanks!

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.)

3 Likes

Awesome!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.