Created
September 13, 2014 22:51
-
-
Save domluna/5c47e495d0518a3e725e to your computer and use it in GitHub Desktop.
Rust pointers, boxing/heap
This file contains 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
// Pretend this is an actual big struct in which it would be | |
// expensive to copy by value. | |
struct BigStruct { | |
one: int, | |
two: int, | |
// etc | |
one_hundred: int, | |
} | |
// An antipattern would be for the return type to be | |
// Box<BigStruct> where Box denotes it's on the heap. | |
fn foo(x: Box<BigStruct>) -> BigStruct { | |
return *x; | |
} | |
fn main() { | |
let x = box BigStruct { | |
one: 1, | |
two: 2, | |
one_hundred: 100, | |
}; | |
// Rust knows to not copy this value due to the "box" | |
// prefix. | |
// | |
// This allows the caller to choose how they want to use | |
// the output | |
// | |
// For example | |
// | |
// let y = foo(x); | |
// | |
// would produce a copy. | |
let y = foo(x); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment