Retrieving Hostname of computer

I am using the gethostname() function and it is working but returning an osstring. I need to convert it to a regular string so that I can use it inside of a REST call I'm building. I've been googling and reading docs but so far nothing is working.

Thanks,

Glenn

There’s a few ways. An OsString may contain non-UTF-8 data so that converting to a String is not always possible. You need to think about how to handle such cases. The into_string method will give you an Err value when the conversion is not possible. The other alternative is to use a “lossy” conversion that will replace non-UTF-8 data with replacement characters “�”. That can be archieved through to_string_lossy on the OsStr type. Converting OsString to String with this could be done through doing x.to_string_lossy().into_owned() on your x: OsString (you can call OsStr methods on an OsString value).

Also note that if you want to ask for help with learning or programming in Rust in the future, the users.rust-lang.org forum is the right place to ask, not this one. This forum is for people who want to discuss the inner working of the rust compiler, or additions/changes to the language or the standard library.

2 Likes