]> git.lizzy.rs Git - rust.git/blob - src/doc/guide-pointers.md
5161dbc6bbb600a57ec32661f0cf9b819ae319cd
[rust.git] / src / doc / guide-pointers.md
1 % The Rust Pointer Guide
2
3 Rust's pointers are one of its more unique and compelling features. Pointers
4 are also one of the more confusing topics for newcomers to Rust. They can also
5 be confusing for people coming from other languages that support pointers, such
6 as C++. This guide will help you understand this important topic.
7
8 # You don't actually need pointers, use references
9
10 I have good news for you: you probably don't need to care about pointers,
11 especially as you're getting started. Think of it this way: Rust is a language
12 that emphasizes safety. Pointers, as the joke goes, are very pointy: it's easy
13 to accidentally stab yourself. Therefore, Rust is made in a way such that you
14 don't need them very often.
15
16 "But guide!" you may cry. "My co-worker wrote a function that looks like this:
17
18 ~~~rust
19 fn succ(x: &int) -> int { *x + 1 }
20 ~~~
21
22 So I wrote this code to try it out:
23
24 ~~~rust{.ignore}
25 fn main() {
26     let number = 5;
27     let succ_number = succ(number);
28     println!("{}", succ_number);
29 }
30 ~~~
31
32 And now I get an error:
33
34 ~~~text
35 error: mismatched types: expected `&int` but found `<generic integer #0>` (expected &-ptr but found integral variable)
36 ~~~
37
38 What gives? It needs a pointer! Therefore I have to use pointers!"
39
40 Turns out, you don't. All you need is a reference. Try this on for size:
41
42 ~~~rust
43 # fn succ(x: &int) -> int { *x + 1 }
44 fn main() {
45     let number = 5;
46     let succ_number = succ(&number);
47     println!("{}", succ_number);
48 }
49 ~~~
50
51 It's that easy! One extra little `&` there. This code will run, and print `6`.
52
53 That's all you need to know. Your co-worker could have written the function
54 like this:
55
56 ~~~rust
57 fn succ(x: int) -> int { x + 1 }
58
59 fn main() {
60     let number = 5;
61     let succ_number = succ(number);
62     println!("{}", succ_number);
63 }
64 ~~~
65
66 No pointers even needed. Then again, this is a simple example. I assume that
67 your real-world `succ` function is more complicated, and maybe your co-worker
68 had a good reason for `x` to be a pointer of some kind. In that case, references
69 are your best friend. Don't worry about it, life is too short.
70
71 However.
72
73 Here are the use-cases for pointers. I've prefixed them with the name of the
74 pointer that satisfies that use-case:
75
76 1. Owned: `Box<Trait>` must be a pointer, because you don't know the size of the
77 object, so indirection is mandatory.
78
79 2. Owned: You need a recursive data structure. These can be infinite sized, so
80 indirection is mandatory.
81
82 3. Owned: A very, very, very rare situation in which you have a *huge* chunk of
83 data that you wish to pass to many methods. Passing a pointer will make this
84 more efficient. If you're coming from another language where this technique is
85 common, such as C++, please read "A note..." below.
86
87 4. Reference: You're writing a function, and you need a pointer, but you don't
88 care about its ownership. If you make the argument a reference, callers
89 can send in whatever kind they want.
90
91 5. Shared: You need to share data among tasks. You can achieve that via the
92 `Rc` and `Arc` types.
93
94 Five exceptions. That's it. Otherwise, you shouldn't need them. Be sceptical
95 of pointers in Rust: use them for a deliberate purpose, not just to make the
96 compiler happy.
97
98 ## A note for those proficient in pointers
99
100 If you're coming to Rust from a language like C or C++, you may be used to
101 passing things by reference, or passing things by pointer. In some languages,
102 like Java, you can't even have objects without a pointer to them. Therefore, if
103 you were writing this Rust code:
104
105 ~~~rust
106 # fn transform(p: Point) -> Point { p }
107 #[deriving(Show)]
108 struct Point {
109     x: int,
110     y: int,
111 }
112
113 fn main() {
114     let p0 = Point { x: 5, y: 10};
115     let p1 = transform(p0);
116     println!("{}", p1);
117 }
118
119 ~~~
120
121 I think you'd implement `transform` like this:
122
123 ~~~rust
124 # struct Point {
125 #     x: int,
126 #     y: int,
127 # }
128 # let p0 = Point { x: 5, y: 10};
129 fn transform(p: &Point) -> Point {
130     Point { x: p.x + 1, y: p.y + 1}
131 }
132
133 // and change this:
134 let p1 = transform(&p0);
135 ~~~
136
137 This does work, but you don't need to create those references! The better way to write this is simply:
138
139 ~~~rust
140 #[deriving(Show)]
141 struct Point {
142     x: int,
143     y: int,
144 }
145
146 fn transform(p: Point) -> Point {
147     Point { x: p.x + 1, y: p.y + 1}
148 }
149
150 fn main() {
151     let p0 = Point { x: 5, y: 10};
152     let p1 = transform(p0);
153     println!("{}", p1);
154 }
155 ~~~
156
157 But won't this be inefficient? Well, that's a complicated question, but it's
158 important to know that Rust, like C and C++, store aggregate data types
159 'unboxed,' whereas languages like Java and Ruby store these types as 'boxed.'
160 For smaller structs, this way will be more efficient. For larger ones, it may
161 be less so. But don't reach for that pointer until you must! Make sure that the
162 struct is large enough by performing some tests before you add in the
163 complexity of pointers.
164
165 # Owned Pointers
166
167 Owned pointers are the conceptually simplest kind of pointer in Rust. A rough
168 approximation of owned pointers follows:
169
170 1. Only one owned pointer may exist to a particular place in memory. It may be
171 borrowed from that owner, however.
172
173 2. The Rust compiler uses static analysis to determine where the pointer is in
174 scope, and handles allocating and de-allocating that memory. Owned pointers are
175 not garbage collected.
176
177 These two properties make for three use cases.
178
179 ## References to Traits
180
181 Traits must be referenced through a pointer, because the struct that implements
182 the trait may be a different size than a different struct that implements the
183 trait. Therefore, unboxed traits don't make any sense, and aren't allowed.
184
185 ## Recursive Data Structures
186
187 Sometimes, you need a recursive data structure. The simplest is known as a 'cons list':
188
189 ~~~rust
190 #[deriving(Show)]
191 enum List<T> {
192     Nil,
193     Cons(T, Box<List<T>>),
194 }
195
196 fn main() {
197     let list: List<int> = Cons(1, box Cons(2, box Cons(3, box Nil)));
198     println!("{}", list);
199 }
200 ~~~
201
202 This prints:
203
204 ~~~text
205 Cons(1, box Cons(2, box Cons(3, box Nil)))
206 ~~~
207
208 The inner lists _must_ be an owned pointer, because we can't know how many
209 elements are in the list. Without knowing the length, we don't know the size,
210 and therefore require the indirection that pointers offer.
211
212 ## Efficiency
213
214 This should almost never be a concern, but because creating an owned pointer
215 boxes its value, it therefore makes referring to the value the size of the box.
216 This may make passing an owned pointer to a function less expensive than
217 passing the value itself. Don't worry yourself with this case until you've
218 proved that it's an issue through benchmarks.
219
220 For example, this will work:
221
222 ~~~rust
223 struct Point {
224     x: int,
225     y: int,
226 }
227
228 fn main() {
229     let a = Point { x: 10, y: 20 };
230     spawn(proc() {
231         println!("{}", a.x);
232     });
233 }
234 ~~~
235
236 This struct is tiny, so it's fine. If `Point` were large, this would be more
237 efficient:
238
239 ~~~rust
240 struct Point {
241     x: int,
242     y: int,
243 }
244
245 fn main() {
246     let a = box Point { x: 10, y: 20 };
247     spawn(proc() {
248         println!("{}", a.x);
249     });
250 }
251 ~~~
252
253 Now it'll be copying a pointer-sized chunk of memory rather than the whole
254 struct.
255
256 # References
257
258 References are the third major kind of pointer Rust supports. They are
259 simultaneously the simplest and the most complicated kind. Let me explain:
260 references are considered 'borrowed' because they claim no ownership over the
261 data they're pointing to. They're just borrowing it for a while. So in that
262 sense, they're simple: just keep whatever ownership the data already has. For
263 example:
264
265 ~~~rust
266 struct Point {
267     x: f32,
268     y: f32,
269 }
270
271 fn compute_distance(p1: &Point, p2: &Point) -> f32 {
272     let x_d = p1.x - p2.x;
273     let y_d = p1.y - p2.y;
274
275     (x_d * x_d + y_d * y_d).sqrt()
276 }
277
278 fn main() {
279     let origin =    &Point { x: 0.0, y: 0.0 };
280     let p1     = box Point { x: 5.0, y: 3.0 };
281
282     println!("{}", compute_distance(origin, p1));
283 }
284 ~~~
285
286 This prints `5.83095189`. You can see that the `compute_distance` function
287 takes in two references, a reference to a value on the stack, and a reference
288 to a value in a box.
289 Of course, if this were a real program, we wouldn't have any of these pointers,
290 they're just there to demonstrate the concepts.
291
292 So how is this hard? Well, because we're ignoring ownership, the compiler needs
293 to take great care to make sure that everything is safe. Despite their complete
294 safety, a reference's representation at runtime is the same as that of
295 an ordinary pointer in a C program. They introduce zero overhead. The compiler
296 does all safety checks at compile time.
297
298 This theory is called 'region pointers' and you can read more about it
299 [here](http://www.cs.umd.edu/projects/cyclone/papers/cyclone-regions.pdf).
300 Region pointers evolved into what we know today as 'lifetimes'.
301
302 Here's the simple explanation: would you expect this code to compile?
303
304 ~~~rust{.ignore}
305 fn main() {
306     println!("{}", x);
307     let x = 5;
308 }
309 ~~~
310
311 Probably not. That's because you know that the name `x` is valid from where
312 it's declared to when it goes out of scope. In this case, that's the end of
313 the `main` function. So you know this code will cause an error. We call this
314 duration a 'lifetime'. Let's try a more complex example:
315
316 ~~~rust
317 fn main() {
318     let mut x = box 5;
319     if *x < 10 {
320         let y = &x;
321         println!("Oh no: {}", y);
322         return;
323     }
324     *x -= 1;
325     println!("Oh no: {}", x);
326 }
327 ~~~
328
329 Here, we're borrowing a pointer to `x` inside of the `if`. The compiler, however,
330 is able to determine that that pointer will go out of scope without `x` being
331 mutated, and therefore, lets us pass. This wouldn't work:
332
333 ~~~rust{.ignore}
334 fn main() {
335     let mut x = box 5;
336     if *x < 10 {
337         let y = &x;
338         *x -= 1;
339
340         println!("Oh no: {}", y);
341         return;
342     }
343     *x -= 1;
344     println!("Oh no: {}", x);
345 }
346 ~~~
347
348 It gives this error:
349
350 ~~~text
351 test.rs:5:8: 5:10 error: cannot assign to `*x` because it is borrowed
352 test.rs:5         *x -= 1;
353                   ^~
354 test.rs:4:16: 4:18 note: borrow of `*x` occurs here
355 test.rs:4         let y = &x;
356                           ^~
357 ~~~
358
359 As you might guess, this kind of analysis is complex for a human, and therefore
360 hard for a computer, too! There is an entire [guide devoted to references
361 and lifetimes](guide-lifetimes.html) that goes into lifetimes in
362 great detail, so if you want the full details, check that out.
363
364 # Returning Pointers
365
366 We've talked a lot about functions that accept various kinds of pointers, but
367 what about returning them? In general, it is better to let the caller decide
368 how to use a function's output, instead of assuming a certain type of pointer
369 is best.
370
371 What does that mean? Don't do this:
372
373 ~~~rust
374 fn foo(x: Box<int>) -> Box<int> {
375     return box *x;
376 }
377
378 fn main() {
379     let x = box 5;
380     let y = foo(x);
381 }
382 ~~~
383
384 Do this:
385
386 ~~~rust
387 fn foo(x: Box<int>) -> int {
388     return *x;
389 }
390
391 fn main() {
392     let x = box 5;
393     let y = box foo(x);
394 }
395 ~~~
396
397 This gives you flexibility, without sacrificing performance.
398
399 You may think that this gives us terrible performance: return a value and then
400 immediately box it up ?! Isn't that the worst of both worlds? Rust is smarter
401 than that. There is no copy in this code. `main` allocates enough room for the
402 `box int`, passes a pointer to that memory into `foo` as `x`, and then `foo` writes
403 the value straight into that pointer. This writes the return value directly into
404 the allocated box.
405
406 This is important enough that it bears repeating: pointers are not for optimizing
407 returning values from your code. Allow the caller to choose how they want to
408 use your output.
409
410 # Related Resources
411
412 * [Lifetimes guide](guide-lifetimes.html)