0

In the section References Are Never Null in the book Programming Rust, they point out there's no analogue to C's NULL. That bit I understand. They then state

Rust won't convert integers to references (outside of unsafe code), so you can't convert zero into a reference.

Does this statement correspond to Rust code that won't compile? What is that code?

Note this compiles fine

let i = 0;
let ri = &i;
println!("{}", i);
println!("{}", ri);

so they're presumably not talking about that.

Note: I think my original question was largely answered by Why is address zero used for the null pointer?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
joel
  • 6,359
  • 2
  • 30
  • 55
  • `NULL` in C is a zero-pointer. The second sentence (quoted) reinforces the first sentence by clarifying that you can't even force a `NULL` by using `0` as a reference. – torstenvl May 06 '19 at 17:16
  • It means that Rust doesn't allow you to do the equivalent of the following C code: `int i = ...; int* p = (int*)i;` – ikegami May 06 '19 at 17:52

2 Answers2

3

At runtime, a reference is just a usize, representing the address of some data in memory. What the book is trying say is that you can't take an integer and then treat it like an address, and then try to get the data that is held there. For example, this fails:

let an_integer: usize = 12345;
let some_value: &bool = an_integer;

With unsafe code, you can do it though:

let an_integer: usize = 12345;
// Very dangerous: transmute unsafely converts between any two types as long as they are the same size:
let some_value: &bool = unsafe { std::mem::transmute(an_integer) };
// Less dangerous, but still dangerous:
let some_value: &bool = unsafe { &*(an_integer as *const bool) };

Peter Hall
  • 53,120
  • 14
  • 139
  • 204
1

They mean stuff like this:

let ref_to_int: &u32 = 42;

It won't compile, because an integer (42) cannot be converted to a reference. You can take a reference to the number 42, but you cannot convert the number 42 itself into a reference.

In the C language, this would be possible, because both memory addresses (pointers) and integers are essentially the same thing (a number). That can cause bugs, so Rust forbids it.

Thomas
  • 174,939
  • 50
  • 355
  • 478