gpt4 book ai didi

memory-management - Rust 会释放被覆盖变量的内存吗?

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

我在 Rust 书中看到,您可以定义两个具有相同名称的不同变量:

let hello = "Hello";
let hello = "Goodbye";

println!("My variable hello contains: {}", hello);

这打印出来:

My variable hello contains: Goodbye

第一次打招呼会发生什么?它会被释放吗?我怎么能访问它?

我知道将两个变量命名为相同的名称会很糟糕,但如果这是偶然发生的,因为我在下面声明了 100 行,这可能会很痛苦。

最佳答案

Rust does not have a garbage collector .

Does Rust free up the memory of overwritten variables?


是的,否则将是内存泄漏,这将是一个非常糟糕的设计决策。重新分配变量时释放内存:
struct Noisy;
impl Drop for Noisy {
fn drop(&mut self) {
eprintln!("Dropped")
}
}

fn main() {
eprintln!("0");
let mut thing = Noisy;
eprintln!("1");
thing = Noisy;
eprintln!("2");
}
0
1
Dropped
2
Dropped

what happens with the first hello


shadowed .
变量引用的数据没有任何“特殊”发生,除了您无法再访问它。当变量超出范围时,它仍然会被删除:
struct Noisy;
impl Drop for Noisy {
fn drop(&mut self) {
eprintln!("Dropped")
}
}

fn main() {
eprintln!("0");
let thing = Noisy;
eprintln!("1");
let thing = Noisy;
eprintln!("2");
}
0
1
2
Dropped
Dropped
也可以看看:
  • Is the resource of a shadowed variable binding freed immediately?

  • I know it would be bad to name two variables the same


    这不是“坏”,这是一个设计决定。我会说像这样使用阴影是一个坏主意:
    let x = "Anna";
    println!("User's name is {}", x);
    let x = 42;
    println!("The tax rate is {}", x);
    使用这样的阴影对我来说是合理的:
    let name = String::from("  Vivian ");
    let name = name.trim();
    println!("User's name is {}", name);
    也可以看看:
  • Why do I need rebinding/shadowing when I can have mutable variable binding?

  • but if this happens by accident because I declare it 100 lines below it could be a real pain.


    不要有太大的功能以至于你“不小心”做了一些事情。这适用于任何编程语言。

    Is there a way of cleaning memory manually?


    您可以调用 drop :
    eprintln!("0");
    let thing = Noisy;
    drop(thing);
    eprintln!("1");
    let thing = Noisy;
    eprintln!("2");
    0
    Dropped
    1
    2
    Dropped
    但是,作为 oli_obk - ker points out ,变量占用的栈内存直到函数退出才会被释放,只有变量占用的资源。 drop 的所有讨论需要展示它的(非常复杂的)实现:
    fn drop<T>(_: T) {}

    What if I declare the variable in a global scope outside of the other functions?


    全局变量永远不会被释放,如果你甚至可以创建它们开始。

    关于memory-management - Rust 会释放被覆盖变量的内存吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63885694/

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