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.
A raw pointer is a pointer whose lifetime isn't controlled by an encapsulating object, such as a smart pointer. A raw pointer can be assigned the address of another non-pointer variable, or it can be assigned a value of nullptr . A pointer that hasn't been assigned a value contains random data.
Rust has a number of different smart pointer types in its standard library, but there are two types that are extra-special. Much of Rust's safety comes from compile-time checks, but raw pointers don't have such guarantees, and are unsafe to use.
Raw pointer are more complicated. Raw pointer arithmetic and casts are "safe", but dereferencing them is not. We can convert raw pointers back to shared and mutable references, and then use them; this will certainly imply the usual reference semantics, and the compiler can optimize accordingly.
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> { ... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With