Rust does not have a garbage collector .
Does Rust save the memory of rewritten variables?
Yes, otherwise it would be a memory leak, which would be a rather awful constructive solution.
what happens with the first greeting
It is shaded .
Nothing "special" happens to the data referenced by the variable, except for the fact that you can no longer get it. It still crashes when the variable goes outside the scope.
Here is the code that is output when each variable is deleted:
struct Noisy; impl Drop for Noisy { fn drop(&mut self) { println!("Dropped") } } fn main() { println!("0"); let thing = Noisy; println!("1"); let thing = Noisy; println!("2"); }
0 1 2 Dropped Dropped
I know that it would be bad to call two variables the same
This is not "bad", it is a design decision. I would say that using a shadow image is a bad idea:
let x = "Anna"; println!("User name is {}", x); let x = 42; println!("The tax rate is {}", x);
Using a similar shadow is reasonable for me:
let name = String::from(" Vivian "); let name = name.trim(); println!("User name is {}", x);
See also:
- Why do I need to double-check / shade when I can bind a variable to a variable?
but if this happens by accident, because I declare that it is 100 lines below, it can be a real pain.
You do not have functions that are so great that you "accidentally" do something. This is applicable in any programming language.
Is there a way to clear memory manually?
You can call drop :
println!("0"); let thing = Noisy; drop(thing); println!("1"); let thing = Noisy; println!("2");
0 Dropped 1 2 Dropped
However, since oli_obk - ker indicates , the memory stack taken by this variable will not be freed until the function exits, but only the resources received by the variable.
All discussions of the drop require a display of a (very complex) implementation:
fn drop<T>(_: T) {}
What if I declare a variable in a global scope outside of other functions?
Global variables are never freed, if you can even create them for starters.