Skip to content

Implement Default for &Option #140808

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

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

camsteffen
Copy link
Contributor

Pretty straightforward, but here is some justification:

I wasn't able to derive Default for my struct containing a &Option<MyType> because I can't implement Default for &Option<MyType> because of the orphan rule. I suppose this is an unusual case because Option<&T> is generally preferred over &Option<T>. But I think adding this is justified for a couple reasons. 1) It removes an unnecessary speed bump. 2) I think there are times when &Option<T> is preferable. In my project I am creating and passing around &Option<MyType> in a lot of places, but only actually using MyType in one place. So it's not worth the ergonomic cost of having to write build_mytype(...).as_ref() instead of &build_mytype(...) in many places.

r? libs

@rustbot rustbot added S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. T-libs Relevant to the library team, which will review and decide on the PR/issue. labels May 8, 2025
@camsteffen camsteffen changed the title Add Default for &Option Implement Default for &Option May 8, 2025
@jieyouxu
Copy link
Member

jieyouxu commented May 8, 2025

r? libs-api

@rustbot rustbot added the T-libs-api Relevant to the library API team, which will review and decide on the PR/issue. label May 8, 2025
@camsteffen
Copy link
Contributor Author

Looking at this more closely, this is not as obvious as I thought. There doesn't seem to be any precedent in std for implementing Default for any reference types excluding unsized types like &str. Is this a slippery slope of adding impl Default to references to all std types? Or is there an obvious solution I'm missing? Also I realized that feature(default_field_values) would be good enough for the use case I encountered. So I'm unsure, but still wonder if adding this is worth it because of the ubiquity of Option and the orphan rule. (I probably should have started a discussion instead of a PR, apologies)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. T-libs Relevant to the library team, which will review and decide on the PR/issue. T-libs-api Relevant to the library API team, which will review and decide on the PR/issue.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

5 participants