1

I'm parsing arguments with clap however I'm slightly confused about how I should structure my program after those arguments are parsed:

What I'm finding is that I need an argument from the command line -- the --verbose flag for instance -- and so I pull that out and now have a boolean that models this, then I end up passing that boolean to all of my functions. It never changes.

Then I'll introduce a new argument on the command line, again I'll want multiple functions to have access to these variables too. So now I convert the clap .get_matches() to a struct that represents the config, and I end up passing that struct to all my functions. It never changes.

I get that we don't want global mutable state. But is there a common idiom for dealing with global state that is only mutated until after the argument parsing? Moreover, is there any guidance on how to handle something like a verbose flag? Do I need to explicitly pass that to every function?


I don't think the above linked questions answers this because I'm not sure I need global mutable state. The comment,

there are indeed disadvise by default, but not when used for a good use case like option program, it's clearly OK tier. – Stargateur 15 mins ago

Is more to the question. What defines "OK tier"? Is it "OK Tier" for example if main occurs in a Tokio binary? What are the safety concerns with doing this? Is there some other method the compiler affords to mutate a variable for the purposes of storing boot state and making it available globally?

Evan Carroll
  • 78,363
  • 46
  • 261
  • 468
  • you can't ask for a global state and then say you don't want a global state XD you need to choice, rust is not magic. – Stargateur Apr 02 '21 at 02:46
  • 1
    @Stargateur I come from a world where that's ok. I'm confused as to why it wouldn't be ok. If the global state (a) isn't mutable after parsing, (b) isn't deallocated (c) happens before other threads/fork spawn, it would seem to me to be the same as global static readonly state which Rust allows. But alas, do I really need mutable state in the sense that I'm pursuing it? I hope I've defined the problem? How do typical rust programs address propagating command-line arguments through the application? – Evan Carroll Apr 02 '21 at 02:50
  • 1
    Does this answer your question? [How do I create a global, mutable singleton?](https://stackoverflow.com/questions/27791532/how-do-i-create-a-global-mutable-singleton) – Stargateur Apr 02 '21 at 02:53
  • there are indeed disadvise by default, but not when used for a good use case like option program, it's clearly OK tier. – Stargateur Apr 02 '21 at 02:54
  • 1
    Sounds like you're after a [`OnceCell`](https://crates.io/crates/once_cell) (which is [en-route](https://github.com/rust-lang/rust/issues/74465) to being included in the standard library). – eggyal Apr 02 '21 at 13:08

0 Answers0