Skip to content

implement Default for raw pointers #571

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

Closed
ChrisDenton opened this issue Apr 6, 2025 · 4 comments
Closed

implement Default for raw pointers #571

ChrisDenton opened this issue Apr 6, 2025 · 4 comments
Labels
ACP-accepted API Change Proposal is accepted (seconded with no objections) api-change-proposal A proposal to add or alter unstable APIs in the standard libraries T-libs-api

Comments

@ChrisDenton
Copy link
Member

ChrisDenton commented Apr 6, 2025

Proposal

Problem statement

Pointers do not implement Default despite there being a natural default value (as shown by is_null). Default is however implemented for AtomicPtr.

Motivating examples or use cases

This works nicely, with all the primitives being zeroed by default:

#[derive(Default)]
struct Test {
    a: [u8; 6],
    b: bool,
    c: char,
    u: u32,
}

But if you add a pointer:

#[derive(Default)]
struct Test {
    a: [u8; 6],
    b: bool,
    c: char,
    u: u32,
    p: *const u8
}

Then you get this error:

error[E0277]: the trait bound `*const u8: Default` is not satisfied
 --> src/lib.rs:7:5
  |
1 | #[derive(Default)]
  |          ------- in this derive macro expansion
...
7 |     p: *const u8,
  |     ^^^^^^^^^^^^ the trait `Default` is not implemented for `*const u8`
  |
  = help: the trait `Default` is implemented for `u8`

To workaround this, each struct containing a pointer can manually implement Default instead of deriving it. The safe way to do so is quite verbose, especially when structs get larger:

impl Default for Test {
    fn default() -> Self {
        Self {
            a: [0; 6],
            b: false,
            c: '\0',
            u: 0,
            p: std::ptr::null()
        }
    }
}

So people will often reach for unsafe to make life easier:

impl Default for Test {
    fn default() -> Self {
        unsafe { std::mem::zeroed() }
    }
}

This is more succinct (if still more verbose than a derive), however now we've introduced a completely unnecessary use of unsafe. This matters because now the guard rails are off. It won't protect you if there are values that cannot be zeroed (there are some lints that can help but they necessarily can't catch everything).

Solution sketch

Note: These will be instantly stable.

impl<T: ?Sized + Thin> Default for *const T {
    fn default() -> Self {
        crate::ptr::null()
    }
}

impl<T: ?Sized + Thin> Default for *mut T {
    fn default() -> Self {
        crate::ptr::null_mut()
    }
}

Alternatives

The status quo.

Links and related work

What happens now?

This issue contains an API change proposal (or ACP) and is part of the libs-api team feature lifecycle. Once this issue is filed, the libs-api team will review open proposals as capability becomes available. Current response times do not have a clear estimate, but may be up to several months.

Possible responses

The libs team may respond in various different ways. First, the team will consider the problem (this doesn't require any concrete solution or alternatives to have been proposed):

  • We think this problem seems worth solving, and the standard library might be the right place to solve it.
  • We think that this probably doesn't belong in the standard library.

Second, if there's a concrete solution:

  • We think this specific solution looks roughly right, approved, you or someone else should implement this. (Further review will still happen on the subsequent implementation PR.)
  • We're not sure this is the right solution, and the alternatives or other materials don't give us enough information to be sure about that. Here are some questions we have that aren't answered, or rough ideas about alternatives we'd want to see discussed.
@ChrisDenton ChrisDenton added api-change-proposal A proposal to add or alter unstable APIs in the standard libraries T-libs-api labels Apr 6, 2025
@scottmcm
Copy link
Member

scottmcm commented Apr 7, 2025

Defaulting raw pointers to null does seem reasonable, as especially repr(C) types that in C would be initialized with = {}; would generally expect to default to null.

That said, I suppose one could argue that the same effect can be obtained with Option<NonNull<T>>, and letting that default to None that's guaranteed to be null in representation.

@clarfonthey
Copy link

I guess that probably the biggest downside to Option<NonNull<T>> is the variance applied even for mutable pointers which might not be desired, although if you're working with raw pointers anyway that's probably not even a consideration, since you're probably just working with POD types anyway.

I kind of feel like Option<NonNull<T>> is probably a substantially more suitable type than raw pointers in most cases, although it definitely is less ergonomic. I don't think that it'd be too harmful to allow Default for raw pointers in the meantime for that reason, especially considering how stuff generated from C bindings will likely use raw pointers instead of Option<NonNull<T>>

@kennytm
Copy link
Member

kennytm commented Apr 7, 2025

previous discussion rust-lang/rfcs#2464

@Amanieu Amanieu added the ACP-accepted API Change Proposal is accepted (seconded with no objections) label Apr 8, 2025
@Amanieu
Copy link
Member

Amanieu commented Apr 8, 2025

We discussed this in the @rust-lang/libs-api meeting and are happy to accept this. I've started an FCP on the PR (rust-lang/rust#139535).

@Amanieu Amanieu closed this as completed Apr 8, 2025
jhpratt added a commit to jhpratt/rust that referenced this issue Apr 19, 2025
Implement `Default` for raw pointers

ACP: rust-lang/libs-team#571

This is instantly stable so we will need an FCP here.

Closes rust-lang/rfcs#2464
ChrisDenton added a commit to ChrisDenton/rust that referenced this issue Apr 19, 2025
Implement `Default` for raw pointers

ACP: rust-lang/libs-team#571

This is instantly stable so we will need an FCP here.

Closes rust-lang/rfcs#2464
rust-timer added a commit to rust-lang-ci/rust that referenced this issue Apr 19, 2025
Rollup merge of rust-lang#139535 - ChrisDenton:default-ptr, r=tgross35

Implement `Default` for raw pointers

ACP: rust-lang/libs-team#571

This is instantly stable so we will need an FCP here.

Closes rust-lang/rfcs#2464
github-actions bot pushed a commit to model-checking/verify-rust-std that referenced this issue Apr 22, 2025
Implement `Default` for raw pointers

ACP: rust-lang/libs-team#571

This is instantly stable so we will need an FCP here.

Closes rust-lang/rfcs#2464
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
ACP-accepted API Change Proposal is accepted (seconded with no objections) api-change-proposal A proposal to add or alter unstable APIs in the standard libraries T-libs-api
Projects
None yet
Development

No branches or pull requests

5 participants