// code snippet 1
1 #[derive(Debug)]
2 struct Foo<'a> {
3 i: &'a String,
4 }
5
6 fn main(){
7 let foo: Foo = Foo {
8 i: &"".to_owned(),
9 };
10 println!("{:?}", foo);
11 }
I feel confused about the code snippet above. What I have learned told me that every value in Rust has an owner, which is responsible for the resource deallocation, this is the mechanism called ownership
.
This aligns great when it comes like this:
// code snippet 2
0 fn main() {
1 let str: String = String::from("hello");
2 }
In code snippet 2
, str
is an owner on the stack, when it goes out of the scope in line 2, the contents on the heap("hello") are deallocated, which is quite clear.
But in code snippet 1
, line 8, "".to_owned()
, we create a String
but don't explicitly bind it to any variable. Instead, we give it to the field i
of foo
in the form of reference
. This is weird, "".to_owned()
doesn't have an owner, but we lend it to someone else.
Then, I decided to create my own struct
instead of using String
from standard library, simulate a similar situation in code snippet 1
, and implement std::ops::Drop
for it to see when is this value freed.
// code snippet 3
1 #![allow(unused)]
2
3 struct MyStruct;
4
5 struct Foo<'a>{
6 i: &'a MyStruct,
7 }
8
9 impl Drop for MyStruct {
10 fn drop(&mut self){
11 println!("MyStruct is dropped.");
12 }
13 }
14
15 impl<'a> Drop for Foo<'a>{
16 fn drop(&mut self){
17 println!("Foo is dropped.");
18 }
19 }
20
21 fn main(){
22 let foo: Foo = Foo{
23 i: &MyStruct,
24 };
25 }
Here is the running result:
# result: (t is my crate name)
➜ t cargo run -q
Foo is dropped.
MyStruct is dropped.
MyStruct
is deallocated after Foo
's deallocation as we can see.
So I am guessing the owner of MyStruct
is foo
, which is also the owner of Foo
struct?
Or the owner of MyStruct
is foo.i
, but can a reference be an owner in Rust?
If you found my question irregular, feel free to point it out :)