gpt4 book ai didi

rust - 了解此Rust借入/指针示例

转载 作者:行者123 更新时间:2023-12-03 11:45:35 26 4
gpt4 key购买 nike

我正在阅读https://blog.rust-lang.org/2015/04/10/Fearless-Concurrency.html,并且有一个有关借用的示例:

Why have two kinds of references? Consider a function like:

fn push_all(from: &Vec<i32>, to: &mut Vec<i32>) {
for i in from.iter() {
to.push(*i);
}
}

This function iterates over each element of one vector, pushing it onto another. The iterator keeps a pointer into the vector at the current and final positions, stepping one toward the other.

What if we called this function with the same vector for both arguments?

push_all(&vec, &mut vec)

This would spell disaster! As we're pushing elements onto the vector, it will occasionally need to resize, allocating a new hunk of memory and copying its elements over to it. The iterator would be left with a dangling pointer into the old memory, leading to memory unsafety (with attendant segfaults or worse).



我不明白悬挂的指针。我也不明白Rust中的 *i是什么意思。我猜这是指针引用。但是,为什么 for遍历原始指针呢? push(*i)如何工作?复制吗?我怎么知道Rust何时复制,借用或拥有?

最佳答案

I didn't understand the dangling pointer.



向量由具有一定容量的缓冲区支持。当您将新项目添加到向量中时,如果后备阵列已满,则需要“腾出更多空间”。

这样做的方法是创建一个比旧数组大的新数组(通常增加1.6或2个系数),将所有内容移到新缓冲区中,然后销毁旧缓冲区。

但是,如果您可以使用相同的向量进行迭代和加法,则在这种情况下,迭代器仍将指向已销毁的缓冲区,这就是“悬空”在这种情况下的意思:指针将“悬空”,因为它将是有效的指向未分配内存的指针(与null指针相反)。

I also don't understand what *i means in Rust. I guess it's pointer deferencing. But why for iterates over raw pointers?


for在Vec上的迭代器上进行迭代,这实际上是 an iterator over a slice。现在,迭代器具有 Item关联类型,这是它们在迭代时产生的事物的类型。对于上面的迭代器,
type Item = &'a T

这意味着 from.iter()是一个迭代器,它对vec中的项目生成引用,在这种情况下为 &i32。如果要从 i32中获取 &i32,则必须取消引用引用,因此要取消引用 *i

And how does push(*i) work?



正常方式?

It copies? How do I know when Rust copies, ~~borrows or~~ owns?



取决于向量的类型(以及应该匹配的参数)。此处 i32是Copy,因此将其复制。

在运行时,实际上并没有什么区别(进行一些优化除外),复制和移动(我想您自己的意思是)是相同的操作,不同之处在于之后是否仍然可以使用“源”。

How do I know when Rust borrows



IIRC Rust可以在两种情况下借用:
  • (如果您告诉它使用&&mut
  • )
  • 如果您调用一个方法(取决于该方法采用&self&mut self还是self,后者是移动或复制,其他两个则是借用)

  • 这样便可以知道何时使用rust 。或复制/移动。

    关于rust - 了解此Rust借入/指针示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61722459/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com