Confused with References in Rust vs C

Been a C programmer for awhile and starting to learn RUST for an upcoming project. I have the following two example codes in C and Rust, respectively


#include <stdio.h>

int main() {
    int x = 10;
    printf("&x = %d  &x = %p", &x, &x);  
// output: 
// warning: format specifies type 'int' but the argument has type 'int *'
// &x(%d): &x = 578563048     *warning*
// &x(%p): &x = 0x7fff227c2be8 
    return 0;


fn main() {
    let x = 2;
    println!("&x = {}", &x);    // output:
                                // &x: &x = 2

I'm constantly seeing &x as an address.
Is this just a language difference that I need to get used to?

Yes, it's a difference in philosophy. In typical Rust code, you rarely work with addresses and raw pointers. So things like testing for equality (the PartialEq trait) and printing (the Display trait) typically "see through" references, or even layers of references, to the underlying non-reference values.

It's not as annoying as it may sound in idiomatic Rust, as non-static references also tend to be short-lived, and pointer-heavy data structures are much more rare or at least abstracted away underneath a library. (Of course, you'll have to get used to idiomatic Rust versus C...)

You can use the Pointer format to print out the address.

fn main() {
    let x = 2;
    println!("&x = {:p}", &x);

You can work with raw pointers and convert them to usize and whatnot (but I don't really recommend it until you've gotten your feet with with safe, idiomatic Rust).


This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.