Rust 和 C/C++ 指针访问结构中值的比较

Comparison between Rust and C/C++ pointers for accessing values in a struct

一些简单的Rust code:

struct Point {
    x: f64,
    y: f64,
}

fn main() {
    let p: &Point = &(Point { x: 0.3, y: 0.4 });
    // println!("{:?}" , p->x); // no sugar here for Rust
    println!("{:?}", (*p).x);
    println!("{:?}", p.x); // sugar?
    // no leak right? thanks Rust
}

还有一些类似C code

#include <stdio.h> 
#include <stdlib.h> 

typedef struct Point Point; 

struct Point {
    float x;
    float y; 
};

int main() {
    Point __tmp = { 0.3, 0.4 };
    Point* p = &__tmp;

    printf("%f\n", p->x); // C sugar for below
    printf("%f\n", (*p).x);
    // below doesn't work because p is a pointer to a point
    //printf("%f", p.x); // error: request for member 'x' in something not a structure or union
    // memory leak at this point right?
    return 0; 
}

似乎 p 是指向两段代码中的 Point 的指针。

我想确保实现 p.x 的 Rust 是(或可以被认为是)语法糖并且我对正在发生的事情没有根本的误解。

这就是他们所说的 别名 的意思吗? p 在 Rust 中更像是一个别名吗?

p.x确实是某种意义上的糖。在进行 method/attribute 查找时,Rust 会自动取消引用任何实现特征 Deref or DerefMut 的类型(取决于上下文需要可变引用还是不可变引用)。

在您的示例中,引用 &Point 实现了 Deref<Target=Point>,因此您的 p.x 表达式扩展为 (*p).x。请注意,这仅适用于指针类型没有自己的名为 x 的 attribute/method(简单引用不是这种情况)。

关于自动取消引用的详细规则。