Default attribute for string fields

my code:

fn main() {}

#[derive(Default)]
pub struct Structer {
    #[default("ok")]
    pub stringy: String,
}

produces this error:

the `#[default]` attribute may only be used on unit enum variants
consider a manual implementation of `Default`rustcClick for full compiler diagnostic

Can u implement this feature?

I think it shouldn't be that hard to impl it. I imagine it would go something like this:

  1. read the token inserted in the default attribute (in this case "ok")
  2. check the type of the token (in this case &str)
  3. check the required type of the field
  4. append ".to_string() to the token
  5. use the modified token as field value like this:
fn default(modified_token: &str) -> String {
    let default = Structer {
        stringy: modified_token.to_string()
    };
    default
}

This isn't something that is implemented by the standard library. You might want to check derivative as an extension of standard derives.

1 Like

I tried it but derivative doesn't seem to support strings (although it does support integers etc). Or maybe I just used the wrong approach

It's a bit more tricky to use derivative with strings, but it is doable:

use derivative::Derivative; 

#[derive(Derivative)]
#[derivative(Default)]
pub struct Structer {
    #[derivative(Default(value=r#""ok".to_owned()"#))]
    pub stringy: String,
}

fn main() {
    assert_eq!(Structer::default().stringy, "ok".to_owned());
}

Playground.

5 Likes

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.