Raw pointers notes


Lately I’ve used raw pointers more, and I have some questions/notes. Observe:

// the trait `std::default::Default` is not implemented for `*const u32`
struct Foo { p: *const u32 }

fn main() {
    struct Bar { x: u32 }
    let mut bar = [Bar{x:10}, Bar{x:20}];
    let ptr1: *mut Bar = &mut bar[0]; // Line 9
    unsafe {
        // ptr1.x = 30; // no field `x` on type `*mut main::Bar`
        (*ptr1).x = 30;

In a very strongly typed language as Rust I think the weak typing of pointer <- ref implicit assignment as shown at line 9 is out of place. Often weak typing gives troubles.

I think I’d like default::Default for raw pointers too. Is this a bad idea?

I also think I’d like automatic fields for raw pointers too (like ptr1.x). I think this has caused no troubles in D language. Is this another bad idea for Rust?


I think the point is that the deref is the unsafe operation. With autoderef (which is what gives you ptr.field) this would get hidden a lot.


Lack of ptr.x support is absolutely intentional, because it can crash the program if the pointer isn’t valid. References are guaranteed to be valid, so for them ref.x is not a problem.

let ptr1: *mut Bar = &mut bar[0]; // Line 9

&mut bar[0] is guaranteed to be valid, so *mut Bar will be, at least temporarily, valid too. More hoops on that line wouldn’t help, because the real trouble starts only later after bar goes out of scope.

The only default that would work for pointers is null, but that’s not a good default in a language that tries not to have nulls anywhere :slight_smile:

Basically, pointers were made inconvenient to use on purpose.