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 中更像是一个别名吗?
一些简单的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 中更像是一个别名吗?