我对 Rust 中指针的工作方式有点困惑。有 ref
、 Box
、 &
、 *
,我不知道它们是如何协同工作的。
以下是我目前的理解:
Box
实际上不是一个指针——它是在堆上分配数据的一种方法,并且在函数参数中传递不大的类型(特别是 trait)。在模式匹配中,ABc0是用来借用你所匹配的东西,而不是拿走它,
let thing: Option<i32> = Some(4);
match thing {
None => println!("none!"),
Some(ref x) => println!("{}", x), // x is a borrowed thing
}
println!("{}", x + 1); // wouldn't work without the ref since the block would have taken ownership of the data
&
is used to make a borrow (borrowed pointer). If I have a function fn foo(&self)
then I'm taking a reference to myself that will expire after the function terminates, leaving the caller's data alone. I can also pass data that I want to retain ownership of by doing bar(&mydata)
.
*
is used to make a raw pointer: for example, let y: i32 = 4; let x = &y as *const i32
. I understand pointers in C/C++ but I'm not sure how this works with Rust's type system, and how they can be safely used. I'm also not sure what the use cases are for this type of pointer. Additionally, the *
symbol can be used to dereference things (what things, and why?).Could someone explain the 4th type of pointer to me, and verify that my understanding of the other types is correct? I'd also appreciate anyone pointing out any common use cases that I haven't mentioned.