A few memory management questions

I am new to rust. As I known, rust has no GC. So I am confused a few things.
First,

struct node {
name: String,
x: float64,
y: float64,
}

let mut n = node{
name: "test".to_string(),
x: 1.0,
y: 1.0,
}

// If I want to change the node's name like this.
n.name = String::from("test1");
//where is the "test".to_string(), will the memory of it be released ?

// If I want to change the node's name like this.
n.name = String::from("test1");
//where is the "test".to_string(), will the memory of it be released ?

And I am confused about some other data structures, such like name is a Vec or some other data which will allocate memory on heap. When it is changed, is the memory been released ?
Another simple example.

let mut x = "where am i".to_string();
x = "you are changed".to_string();
//where is the "where am i".to_string() now?

//where is the "where am i".to_string() now? is it been released?

And I am confused about many examples. Such as vector and hashmap, hashmap 's key's value is always changed, will the value's memory be released? If someone knows it ,please help me! thx!

Structs and collections own its fields/elements. When the field/element is overwritten, the previous value is not owned by anyone so it will be dropped just before the assignment.

Note that the struct/collection owns the field/element doesn't implies they can't stores the references. Vec<&String> owns the &Strings but the &String doesn't own its buffer since it's just an reference.

Ok, I got it, how about the simple example? What if a string value changed? Is it the same thing?

let mut x = "where am i".to_string();
x = "you are changed".to_string();
//where is the "where am i".to_string() now?

Yes. Variables owns its value.

1 Like