Search code examples
stringrusttype-conversionintegerposix

How do I convert an OsString to a u16 on POSIX systems?


I'm grabbing a string from the environment via std::env::var_os, and I want to attempt to convert the resulting OsString received from matching the returned Option<OsString> into a u16. How could I go about doing this in a way that works on POSIX systems?


Solution

  • If you'd like to convert an Option<OsString> to an Option<u16> you can use this function:

    use std::ffi::OsString;
    
    fn to_integer(maybe_os_string: Option<OsString>) -> Option<u16> {
        if let Some(os_string) = maybe_os_string {
            if let Ok(string) = os_string.into_string() {
                if let Ok(integer) = string.parse::<u16>() {
                    return Some(integer);
                }
            }
        }
        None
    }
    

    playground

    It should work regardless of underlying operating system. The caller of the function would have to handle the None case if the OsString can't be parsed as a u16.