Rust那些事之Rust引用

准备搞起一个《Rust那些事》,一起来学习呀~

Rust引用

1.引用

Rust中,使用&T表示类型T的引用类型,跟C++的引用比较来说不太一样,简单理解:等同于const T*

Rust版:

pub fn get_rf() {
  let mut a : i32 = 1;
  let mut b : i32 = 2;
  let c : i32 = 3;
  let d : &mut i32 = &mut a; // d points to a now
  *d = 2; //OK, change a
  // d = &mut b; // ILLEGAL, d is not mutable
  let mut e : &mut i32;
  // e = &a; // illegal d already has a mutable reference to a
  e = &mut b; 
  // e = &mut c; // Illegal, c is not mutable
}

C++版:

void get_rf() {
  int a = 1, b = 2;
  const int c = 3;
  int* const d = &a; // d can't change, but it points to something that can
  *d = 2; // OK
  //d = &b; // ILLEGAL
  int* e; // e can change, as can the thing it points to
  // e = &a, legal in c++ since there's no borrow checker
  e = &b;  // OK, e points to b;
  e = &c; // ILLEGAL, c is const
}

例子中**&mut称为可变引用**,由于&创建出来的引用是只读,所以这里可以用&mut

2.解引用

Rust自动解引用:

  • Rust版:

let a = vec![1,2,3];
let b = &a;
let c = &b;
let one = rrv[0];
  • C++版:

const vector<int> a{1, 2, 3};
const vector<int>* const b = &a;
const vector<int> *const * const c = &b;
int one = (**c)[0];

可以看到C++需要手动解。

像遇到.调用一般自动解引用,诸如:

r.first_name
numbers.sort();

手动解引用:

如果你要给一个引用赋值,必须手动解。

let mut a = 5;
let rra = &mut &mut a;
// rra = 6; // ILLEGAL, must derefence manually
**rra = 6;

最后,建立了一个小群,一起来交流吧~

0169adc4fdd45176af65c196036949af.jpeg

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值