Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does `std::env::args` return an iterator of `String` instead of `&'static str`?

Tags:

rust

What I remember from my operating systems class is that, at least in the OS we were working on, command-line arguments are stored somewhere in the process' address space. If that is the case, then couldn't std::env::Args be an iterator over &'static str? Or if the encoding of the strings is not necessarily UTF-8 and is operating-system dependent, couldn't std::env::ArgsOs be an iterator over &'static OsStr?

like image 755
Michael Hewson Avatar asked Feb 20 '18 00:02

Michael Hewson


1 Answers

[...] at least in the OS we were working on [...]

That's your answer. Just because one OS stores command-line arguments literally in memory, doesn't mean they all do. More than that, what's to say they store them in the exact same format that str expects?

The trivial example of this is Windows, where the command-line is a single potentially invalid UTF-16 string returned from a function call: there is no way to turn this into a &'static str.

So, the API is designed to return an owned string on the basis that it has to be consistent across platforms, and it doesn't know what it might have to do to get the command-line arguments into a usable format.

like image 123
DK. Avatar answered Nov 15 '22 08:11

DK.