Created
August 25, 2013 16:41
-
-
Save SiegeLord/6334876 to your computer and use it in GitHub Desktop.
Ownership tricks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| struct Resource(int); | |
| struct Owner | |
| { | |
| target: ~Resource | |
| } | |
| impl Owner | |
| { | |
| fn set_target(&mut self, new_target: ~Resource) | |
| { | |
| self.target = new_target; | |
| } | |
| fn clear_target(&mut self) -> ~Resource | |
| { | |
| let mut other = ~Resource(0); // Can I avoid this allocation | |
| std::util::swap(other, self.target); | |
| other | |
| } | |
| } | |
| fn main() | |
| { | |
| let mut owner = Owner{target: ~Resource(0)}; | |
| let res = ~Resource(1); | |
| owner.set_target(res); | |
| let res = owner.clear_target(); | |
| printfln!(res); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment