Rust 有什么而不​​是垃圾收集器? [英] What does Rust have instead of a garbage collector?

查看:45
本文介绍了Rust 有什么而不​​是垃圾收集器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道 Rust 没有垃圾收集器,我想知道当绑定超出范围时如何释放内存.

I understand Rust doesn't have a garbage collector and am wondering how memory is freed up when a binding goes out of scope.

所以在这个例子中,我知道 Rust 会在超出范围时回收分配给 'a' 的内存.

So in this example, I understand that Rust reclaims the memory allocated to 'a' when it goes out of scope.

{
    let a = 4
}

我遇到的问题首先是这是如何发生的,其次这不是一种垃圾收集吗?它与典型"垃圾收集有何不同?

The problem I am having with this, is firstly how this happens, and secondly isn't this a sort of garbage collection? How does it differ from 'typical' garbage collection?

推荐答案

垃圾收集通常会定期或按需使用,例如堆接近满或高于某个阈值.然后根据算法查找未使用的变量并释放它们的内存.

Garbage collection is typically used periodically or on demand, like if the heap is close to full or above some threshold. It then looks for unused variables and frees their memory, depending on the algorithm.

Rust 会知道变量何时超出范围或其生命周期在编译时结束,从而插入相应的 LLVM/汇编指令以释放内存.

Rust would know when the variable gets out of scope or its lifetime ends at compile time and thus insert the corresponding LLVM/assembly instructions to free the memory.

Rust 还允许某种垃圾收集,例如 原子引用计数.

Rust also allows some kind of garbage collection, like atomic reference counting though.

这篇关于Rust 有什么而不​​是垃圾收集器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆