ideasman42
ideasman42

Reputation: 48178

How to implement `Default` for a raw pointer?

When using raw points in a struct, Rust doesn't allow to derive from Default.

eg:

#[derive(Default)]
struct Foo {
    bar: *mut Foo,
    baz: usize,
}

Reports

error[E0277]: the trait bound `*mut Foo: std::default::Default` is not satisfied

I tried this but it doesn't work:

impl Default for *mut Foo {
    fn default() -> *mut Foo {
        ptr::null_mut()
    }
}

This gives an error:

impl doesn't use types inside crate

Is there a way to declare Default for the raw pointer?

Otherwise I'll have to write explicit default functions for any struct which contains a raw pointer, OK in this example, but for larger structs it can be tedious, so I'd like to be able to avoid it in some cases.

Upvotes: 8

Views: 1173

Answers (1)

Lukas Kalbertodt
Lukas Kalbertodt

Reputation: 88916

Is there a way to declare Default for the raw pointer?

No, currently there isn't. Either the trait or the type needs to be defined in the crate, in which the trait-impl is written (so called "orphan rules").

However, you don't need to manually implement Default for all of your types containing a pointer. You can create a new type, which wraps a raw pointer and does implement Default. Then you can just use this new type in all of your structs and simply derive Default.

struct ZeroedMutPtr<T>(pub *mut T);

impl<T> Default for ZeroedMutPtr<T> { ... } 

Upvotes: 6

Related Questions