Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Feature Request] default value from function (or closure) #1453

Closed
pbzweihander opened this issue Apr 11, 2019 · 6 comments
Closed

[Feature Request] default value from function (or closure) #1453

pbzweihander opened this issue Apr 11, 2019 · 6 comments
Labels
E-help-wanted Call for participation: Help is requested to fix this issue.

Comments

@pbzweihander
Copy link

pbzweihander commented Apr 11, 2019

It would be great if I can make default values from functions, not literals.

For example, if I want to get some options from args, but if not exists, I want to fallback to environment variables, and if not exists either, I want to panic. Like this:

Arg::with_name("some-arg").default_from(|| {
    std::env::var("SOME_ARG").expect("Some arg is not found neither opt nor envvar")
));

If this is possible, I can make the 'environment variable part' lazily evaluated!

@ananthp
Copy link

ananthp commented May 2, 2019

I thought it's already possible to generate a value from a function and use it as default value for an argument:

Arg::with_name("path")
    .default_value(generate_default_path())

The problem is:

  • generate_default_path() dynamically constructs a value. It has to return String, not &str, but default_value() expects &str
  • .default_value(&generate_default_path()) has a lifetime issue. The borrowed value will expire by the time get_matches() returns the value. So, the parsed arguments can not be used.

@frol
Copy link

frol commented May 13, 2019

Another problem of .default_value(generate_default_path()) is laziness, i.e. generate_default_path() will be executed even if the value was provided.

@CreepySkeleton
Copy link
Contributor

CreepySkeleton commented Feb 1, 2020

Does anybody really need this? I doubt this calculations can ever be complex.

@frol
Copy link

frol commented Feb 1, 2020

@CreepySkeleton The calculations could be non-complex, but they may involve some remote resource fetching or file reading, which you would prefer to avoid.

@CreepySkeleton CreepySkeleton added the E-help-wanted Call for participation: Help is requested to fix this issue. label Feb 1, 2020
@pksunkara
Copy link
Member

I think this can be done with the hook feature that was described in #1634 (comment). Do you guys agree?

@CreepySkeleton
Copy link
Contributor

Yes, indeed. Closing in favor of #1634 (comment)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
E-help-wanted Call for participation: Help is requested to fix this issue.
Projects
None yet
Development

No branches or pull requests

5 participants