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

implement Default for arrays #25169

Closed
vks opened this issue May 7, 2015 · 6 comments
Closed

implement Default for arrays #25169

vks opened this issue May 7, 2015 · 6 comments
Labels
C-enhancement Category: An issue proposing an enhancement or a PR with one.

Comments

@vks
Copy link
Contributor

vks commented May 7, 2015

Something like

impl<T: Default> for [T; 2] {                                                       
    fn default() -> [T; 2] {                                                        
        [Default::default(), Default::default()]                                    
    }                                                                               
}

for N=0..33 should be added to src/libcore/default.rs. The question is how to do that with a macro.

@lilyball
Copy link
Contributor

lilyball commented May 7, 2015

What's special about N=0..33?

@vks
Copy link
Contributor Author

vks commented May 7, 2015

Due to lack of generics over integers, we cannot implement it for all N. Typically traits on arrays in the standard library are implemented for N=0..33, see for example Eq.

@steveklabnik steveklabnik added A-libs C-enhancement Category: An issue proposing an enhancement or a PR with one. labels May 7, 2015
@nham
Copy link
Contributor

nham commented May 8, 2015

I looked at this a bit today and I'm stuck. Here's one way to do it, but it requires an extraneous Copy bound on T (inside libcore/array.rs macro):

        impl<T: Copy + Default> Default for [T; $N] {
            #[inline]
            fn default() -> [T; $N] {
               [Default::default(); $N]
            }                                                                               
        }

Not sure if there's any way to achieve the same effect as array initialization without requiring Copy.

@vks
Copy link
Contributor Author

vks commented May 9, 2015

You could write [Defaul::default(), Default::default(), ...] instead.

@shepmaster
Copy link
Member

I think you have to write it out as [Default::default(), Default::default(), ...]. If the Default implementation actually calls something stateful, like rand, you presumably would want there to be different random values for each item.

@apasel422
Copy link
Contributor

This was implemented in #27825 and can be closed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
C-enhancement Category: An issue proposing an enhancement or a PR with one.
Projects
None yet
Development

No branches or pull requests

6 participants