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

Add default value for properties #775

Closed
mdtusz opened this issue Dec 5, 2019 · 0 comments · Fixed by #881
Closed

Add default value for properties #775

mdtusz opened this issue Dec 5, 2019 · 0 comments · Fixed by #881
Labels
feature-request A feature request

Comments

@mdtusz
Copy link
Contributor

mdtusz commented Dec 5, 2019

Context

When creating a component, there are often cases where the component can and should function without having an explicit value provided as a prop. While currently, props structs will provide a default value for a field if Default is implemented for it's type, this is not always the value that is desired or required by the component. For example, a bool will default to false and numerics will default to 0. In many sitiuations, a component will require alternative defaults than the type defaults.

Possibilities

With serde, default values can be provided using a syntax like

#[derive(Deserialize, Debug)]
struct Request {
    // Use the result of a function as the default if "resource" is
    // not included in the input.
    #[serde(default = "default_resource")]
    resource: String,
}

fn default_resource() -> String {
    "/".to_string()
}

A similar approach could be taken for property structs:

#[derive(Properties)]
struct MyProps {
    #[props(default = "default_value")]
    value: u32,
    #[props(default = "always_true")]
    enabled: bool
}

fn default_value() -> u32 {
  100
}

fn always_true() -> bool {
  true
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feature-request A feature request
Projects
None yet
2 participants