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

FR: derive Default also for Structs with non implementers of Default #3761

Closed
thkoch2001 opened this issue Jan 13, 2025 · 2 comments
Closed

Comments

@thkoch2001
Copy link

Given a struct:

struct Outlink {
    rel: Option<String>,
    context: Context,
    url: Url,                // Url does not implement Default !!!
    redirect_count: usize,
    content_type: Option<String>,
    // ... more members implementing Default
}

I want to be able to:

#[derive(Default)]
struct Outlink {
    rel: Option<String>,
    context: Context,
    #[default_from=EXPRESSION]
    url: Url,
    redirect_count: usize,
    content_type: Option<String>,
    // ... more members implementing Default
}

Where EXPRESSION is any valid expression of type Url, e.g. Url.parse("file:///dummy").unwrap().

This satisfies at least two scenarios:

a) There is no need anymore for trivil constructors, as they can instead be written as:

    let url = ...;
    let outlink = Outlink {
        url .. Outlink::Default()
    }

b) Types that have no intrinsic default value but do have a sensible default value in the context of another type.

@kennytm
Copy link
Member

kennytm commented Jan 13, 2025

if Url::parse is a const fn, then #3681 already covered it.

@thkoch2001
Copy link
Author

Yes! Thank you! The syntax in #3681 is also much less surprising than mine.

For the record, I actually ended up with splitting the struct in two, which also makes more sense semantically in my app:

#[derive(Default)]
struct Inlink {
    rel: Option<String>,
    context: Context,
    redirect_count: usize,
    content_type: Option<String>,
}

struct Outlink {
    url: Url,
    i: Inlink,
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants