Search code examples
stringrusttype-conversionc-strings

How do I convert a CString into a String with Rust?


I have a CString that I'm reading from disk. I created it with CStr::from_bytes_until_nul. My end goal though is to have a String, not a CString. I'm trying to store my CString into a struct that requires String. Is there a method to convert from CString to String?

A CString is owned and seems to,

  • Guarantee there is no inner \0
  • Guarantee there is a terminal \0

A String is also owned. it seems to,

  • Guarantee the contents are utf8.

Why isn't there a .try_into() from CString to String, that pulls off the terminal \0 and wraps str::from_utf8(mycstring)?


Solution

  • There is the method into_string on CString itself that does exactly what you wanted to do.