2020-09-26: What is the difference between & in rust and & in c++?

Fu Ge's answer 2020-09-26: #福大Architects Daily One Question#

Variable definition: C++ is an alias. Rust is a pointer.
Take address and bitwise AND, C++ and rust are the same.

The c++ test code is as follows:

#include <iostream>
struct Point {
    
    
    int x;
    int y;
};

int main()
{
    
    
    Point p1 = {
    
     25,25 };
    printf("p1.x address:%d\r\n", &p1.x);
    printf("p1 address:%d\r\n", &p1);
    Point& p2 = p1;
    printf("p2.x address:%d\r\n", &p2.x);
    printf("p2 address:%d\r\n", &p2);
    printf("p1和p2地址相同,说明p2起到了别名的作用。p2.x和p2地址相同,说明p2保存的是内容,而不是地址。\r\n");
    std::system("pause");
    return 0;
}

The running results are as follows: The
Insert picture description here
rust test code is as follows:

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

fn main() {
    
    
    let p1 = Point {
    
     x: 25, y: 25 };
    println!("p1.x address: {:p}", &p1.x);
    println!("p1 address: {:p}", &p1);
    let p2: &Point = &p1;
    println!("p2.x address: {:p}", &p2.x);
    println!("p2 address: {:p}", &p2);
    println!("p1和p2地址不同,说明p2不是p1的别名。p2.x和p2地址不同,说明p2是指针。");
}

The results are as follows:
Insert picture description here


comment

Guess you like

Origin blog.csdn.net/weixin_48502062/article/details/108814816