Skip to main content

rust mut and mut& and &

背景

rust 很多 相关的语法,开始容易弄混 & 以及 &mut 在不同部分的语义不一样

首先我目前知道的有三个

let-statements

首先介绍 let-statementsmut

  • mut 可赋值
  • 没有mut 不可以赋值

let-statements

fn main() {
let x = 1;
let mut y = 2; // 可赋值和不可赋值
y = x;
}

pointer type

pointer type

Pointer types 有三种

  • Shared references (&)
  • Mutable references (&mut)
  • Raw pointers (*const and *mut)

这个就算在需要类型的时候可以使用

Shared references 例子:

let b = 2;
let x : &i32 = &b; //这里 &i32 就是指定了类型 Shared references

Mutable references例子

&mut i32 是类型 可变的引用
&mut bBorrow operators

  let mut b = 2;
let x : &mut i32 = &mut b; //这里有两个 &mut , &mut i32 叫做 Mutable references ,&mut b 叫做Borrow operators