Operating systems use their own string encoding that they use for file system paths. This means that the Rust strings cannot be used directly with operating systems. Here are the differences between Rust and the main operating systems:
Rust’s strings are UTF-8 and may contain NULL characters.
Unix’s strings are NULL terminated byte strings interpreted as UTF-8 in many cases.
Windows’ strings are NULL terminated 16-bit strings interpreted as UTF-16 in many cases.
OsStr and
OsString
(part of the std::ffi module) allow to make the transition between
Rust’s strings and the operating system:
OsStringstores its string on the heap.OsStris a slice on an operating system’s string.
See Table 1 and Table 2 for lists of the most useful methods for these both types.
Table 1:Some methods of OsStr
Method | Description |
|---|---|
| Returns an object that represent the current string and can be safely printed, eliminating non-Unicode characters. |
| Returns |
| Returns |
| Returns the string’s length. |
| Creates a new |
| Puts ASCII characters in lowercase. |
| Puts ASCII characters in uppercase. |
| Returns an |
| Returns an |
| Returns a copy of this string as an |
| Returns a string slice of this string is a valid UTF-8 string,
otherwise returns |
| Converts this string into a UTF-8 string, replacing non-UTF-8
characters by the Unicode |
Table 2:Some methods of OsString
Method | Description |
|---|---|
| Converts to an |
| Removes all content. |
| Converts into a |
| Converts into a |
| Converts into a |
| Consumes the internal string and returns it as a |
| Appends a string to this |
use std::ffi::OsString;
OsString::from("foo.txt")"foo.txt"use std::ffi::OsString;
let s: OsString = "foo.txt".into();
s"foo.txt"use std::ffi::OsString;
let mut s = OsString::new();
s.push("abc/def.txt");
sCouldn't automatically determine type of variable `s`.
Please give it an explicit type.