CS110L-Lab/week2/ownership.txt
ridethepig 65fe3e800b rdiif
2023-02-23 07:31:06 +00:00

42 lines
1.1 KiB
Plaintext

Example 1:
```
fn main() {
let mut s = String::from("hello");
let ref1 = &s;
let ref2 = &ref1;
let ref3 = &ref2;
s = String::from("goodbye");
println!("{}", ref3.to_uppercase());
}
```
Answer:
This code won't compile. Reference to mutable variable 's' is used later, so it shouldn't change before all borrows are returned to 's'.
If the 'println' is set above assignment of 's', it should be ok.
Example 2:
```
fn drip_drop() -> &String {
let s = String::from("hello world!");
return &s;
}
```
Answer:
This code won't compile. It returns a reference, but when the function leaves, the owner will be dropped, the refernece becomes dangling, this is unacceptable.
Example 3:
```
fn main() {
let s1 = String::from("hello");
let mut v = Vec::new();
v.push(s1);
let s2: String = v[0];
println!("{}", s2);
}
```
Answer:
The ownership is transfered to `v` after push, that's good.
However, `let s2 = v[0]` requires for a ownership move(or Copy trait which String doesnt have), but 'Index operator []' returns a reference(&self::Output), so it couldn't been moved.