Std::env::args() как безопасно получить переданные аргументы

В документации функции std::env::args() написано, что первый (под индексом ноль) аргумент может не существовать. Что это значит? То что нулевой индекс будет пустой строкой или нулевого индекса не будет вообще, и он будет равен первому переданному бинарнику аргументу? Если 1 аргумент всегда занимает нулевой индекс, тогда его можно игнорировать, но если он может занимать индекс опционально, как тогда безопасно получить аргументы? Как тогда понять, под каким индексом находится первый переданный аргумент - под нулевым или под первым

TL;DR: arg0, like all other arguments comes from the caller and it's not guaranteed that it would point to the binary that is now executing and it may not even exist at all.

This has nothing to do with Rust, that's just how POSIX API works. Documentation just mentions that because Rust doesn't try to do any extra efforts to find it's binary, arg0 is returned exactly like it's passed to exec.

And if you look on the exec function you'll see that arg0 is not special.

When program calls exec to execute another program it may pass literally anything in the arg0. It may be pass to executable, first argument, whatever.

Usually programs pass argument to the executable itself in arg0, but that's not guaranteed by POSIX and your program may not rely on it (it's shell, most must and that's different things, see RFC2119.

But I didn’t understand the main thing from your answer

Will the zero index of the Args structure always be occupied by an arbitrary value?

Or could index zero be occupied by an argument passed through the console?

I just don’t understand what the expression “May not exist” means. This may mean that std::env::args().nth(0) will return an empty string. Or maybe it means that it will return the first argument passed through the console

Or could index zero be occupied by an argument passed through the console?

No, it will not, because this is how the convention works. The point the documentation is making is that it is a convention, not a guarantee provided by the operating system.

A program can execute your program and pass arbitrary data in all positions. But if it wants to successfully pass options/inputs to your program, it will do so starting at position 1.

I just don’t understand what the expression “May not exist” means. This may mean that std::env::args().nth(0) will return an empty string.

It means that std::env::args().nth(0) might return None — that 0 args have been passed.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.