Does Rust free up the memory of overwritten variables?

Rust does not have a garbage collector.

Does Rust free up the memory of overwritten variables?

Yes, otherwise it’d be a memory leak, which would be a pretty terrible design decision. The memory is freed when the variable is reassigned:

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

It is shadowed.

Nothing “special” happens to the data referenced by the variable, other than the fact that you can no longer access it. It is still dropped when the variable goes out of scope:

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

See also:

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

It’s not “bad”, it’s a design decision. I would say that using shadowing like this is a bad idea:

let x = "Anna";
println!("User's name is {}", x);
let x = 42;
println!("The tax rate is {}", x);

Using shadowing like this is reasonable to me:

let name = String::from("  Vivian ");
let name = name.trim();
println!("User's name is {}", name);

See also:

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

Don’t have functions that are so big that you “accidentally” do something. That’s applicable in any programming language.

Is there a way of cleaning memory manually?

You can call drop:

eprintln!("0");
let thing = Noisy;
drop(thing);
eprintln!("1");
let thing = Noisy;
eprintln!("2");
0
Dropped
1
2
Dropped

However, as oli_obk – ker points out, the stack memory taken by the variable will not be freed until the function exits, only the resources taken by the variable.

All discussions of drop require showing its (very complicated) implementation:

fn drop<T>(_: T) {}

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

Global variables are never freed, if you can even create them to start with.

Leave a Comment