以下中的(a(和(b(之间有什么区别
let a: Box<i32> = Box::new(1); // (a)
let mut a: Box<i32> = Box::new(1); // (b)
a = Box::new(2); // (c)
*a = 3; // (d)
(a( 相当于C++中的以下内容
int const * const a = new int(1);
和(b(相当于
int * a = new int(1);
在Rust中,有类似的东西吗
int const * a = new int(1); // this allows (c) but not (d)
或
int * const a = new int(1); // this allows (d) but not (c)
在Rust中,有什么等效于的东西吗
不使用Box
(或大多数其他智能指针(,因为它完全没有用。Box
是唯一的指针,(c(和(d(之间没有函数/可观察的差异。
不过,您可以使用引用来执行此操作:您可以有mut x: &T
、mut x: &mut T
、x: &T
或x: &mut T
。
#[allow(unused_assignments)]
fn foo(mut v1; u8, mut v2: u8) {
let a = &mut v1;
a = &mut v2; // doesn't compile, `a` is an immutable binding
*a = v2; // compiles, `a` is bound to a mutable reference
let mut b = &v1;
b = &v2; // compiles, `b` is a mutable binding
*b = v2; // doesn't compile, `b` binds is bound to an immutable reference
}