How to implement "Default" for a raw pointer?

When using the starting points in the structure, Rust does not allow to get the default value.

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 does not 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 a raw pointer?

Otherwise, I will have to write explicit Default functions for any struct that contains a raw pointer, in this example OK, but for large structures this can be tedious, so I would like to be able to avoid this in some cases.

+5
source share
1 answer

Is there a way to declare a default value for a raw pointer?

No , currently not. In the box, either a trait must be defined, or the type in which the trait-impl is written (the so-called "orphan rules").

However, you do not need to manually implement Default for all of your types that contain a pointer. You can create a new type that wraps a raw pointer and implements Default . Then you can just use this new type in all your structures and just get Default .

 struct ZeroedMutPtr<T>(pub *mut T); impl<T> Default for ZeroedMutPtr<T> { ... } 
+6
source

Source: https://habr.com/ru/post/1258930/


All Articles