Skip to content

default_value from lazy Default #150

@swfsql

Description

@swfsql

(Hello, I'm still not sure if this should be on structopt or clap-rs..),

This is a feature request so default_value may be used without any value (like short/long), and be lazily derived from Default itself.

Quick example:

from this:

#[derive(Clone, Debug, StructOpt)]
pub struct Config {
    #[structopt(raw(default_value = "&DEFAULT_CONFIG_BIND_ADDR_STR"))]
    pub bind_addr: SocketAddr,
}

impl Default for Config {
    fn default() -> Self {
        Self {
            bind_addr: FromStr::from_str("127.0.0.1:8080").unwrap()
        }
    }
}

// interface between `Default::default()` and (structopt) `default_value`
lazy_static! {
    static ref DEFAULT_CONFIG: Config = Config::default();
    static ref DEFAULT_CONFIG_BIND_ADDR_STR: String = DEFAULT_CONFIG.bind_addr.to_string();
    // (for fields that has no to_string(), I'm "manually" implementing (interfacing) it with some serde serialization by implementing Display)
}
// lazy_static is needed so &'static str may be used. I don't know how different parsing choices would be dealt with..

into this:

#[derive(Clone, Debug, StructOpt)]
#[structopt(default_value)]
pub struct Config {
    pub bind_addr: SocketAddr,
}

impl Default for Config {
    fn default() -> Self {
        Self {
            bind_addr: FromStr::from_str("127.0.0.1:8080").unwrap()
        }
    }
}

Sorry in advance if this is actually a bad design choice (then I should have no intention of asking for such feature), and that I can't really point into any macro derivation specifics. It's magic !!

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementWe would love to have this feature! Feel free to supply a PR

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions