【发布时间】:2020-09-17 18:45:59
【问题描述】:
我正在阅读 Rust 文档,但似乎无法完全理解正在发生的事情。比如在here上面我看到了下面的例子:
// This function takes ownership of a box and destroys it
fn eat_box_i32(boxed_i32: Box<i32>) {
println!("Destroying box that contains {}", boxed_i32);
}
// This function borrows an i32
fn borrow_i32(borrowed_i32: &i32) {
println!("This int is: {}", borrowed_i32);
}
fn main() {
// Create a boxed i32, and a stacked i32
let boxed_i32 = Box::new(5_i32);
let stacked_i32 = 6_i32;
// Borrow the contents of the box. Ownership is not taken,
// so the contents can be borrowed again.
borrow_i32(&boxed_i32);
borrow_i32(&stacked_i32);
{
// Take a reference to the data contained inside the box
let _ref_to_i32: &i32 = &boxed_i32;
// Error!
// Can't destroy `boxed_i32` while the inner value is borrowed later in scope.
eat_box_i32(boxed_i32);
// FIXME ^ Comment out this line
// Attempt to borrow `_ref_to_i32` after inner value is destroyed
borrow_i32(_ref_to_i32);
// `_ref_to_i32` goes out of scope and is no longer borrowed.
}
// `boxed_i32` can now give up ownership to `eat_box` and be destroyed
eat_box_i32(boxed_i32);
}
我相信的事情:
- eat_box_i32 采用指向 Box 的指针
- 这一行
let boxed_i32 = Box::new(5_i32);使得 boxed_i32 现在包含一个指针,因为 Box 不是原语
我不明白的事情:
- 为什么我们需要用 & 号调用
borrow_i32(&boxed_i32);? boxed_i32 不是已经是指针了吗? - 在这一行:
let _ref_to_i32: &i32 = &boxed_i32;为什么需要在右侧使用 & 符号? boxed_i32 不是已经是地址了吗? - 怎么可以用指向 Box 的指针和指向 i32 的指针来调用 borrow_i32 ?
【问题讨论】:
标签: rust