准备搞起一个《Rust那些事》,一起来学习呀~
Rust引用
1.引用
Rust中,使用&T
表示类型T的引用类型,跟C 的引用比较来说不太一样,简单理解:等同于const T*
,
Rust版:
代码语言:javascript复制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 版:
代码语言:javascript复制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();
手动解引用:
如果你要给一个引用赋值,必须手动解。
代码语言:javascript复制let mut a = 5;
let rra = &mut &mut a;
// rra = 6; // ILLEGAL, must derefence manually
**rra = 6;