@@ -1284,6 +1284,73 @@ For a more in-depth explanation of borrowed pointers, read the
1284
1284
1285
1285
[borrowtut]: tutorial-borrowed-ptr.html
1286
1286
1287
+ ## Dereferencing pointers
1288
+
1289
+ Rust uses the unary star operator (`*`) to access the contents of a
1290
+ box or pointer, similarly to C.
1291
+
1292
+ ~~~
1293
+ let managed = @10 ;
1294
+ let owned = ~ 20;
1295
+ let borrowed = &30;
1296
+
1297
+ let sum = * managed + * owned + * borrowed;
1298
+ ~~~
1299
+
1300
+ Dereferenced mutable pointers may appear on the left hand side of
1301
+ assignments, in which case the value they point to is modified.
1302
+
1303
+ ~~~
1304
+ let managed = @mut 10;
1305
+ let owned = ~ mut 20;
1306
+
1307
+ let mut value = 30;
1308
+ let borrowed = &mut value;
1309
+
1310
+ * managed = * owned + 10;
1311
+ * owned = * borrowed + 100;
1312
+ * borrowed = * managed + 1000;
1313
+ ~~~
1314
+
1315
+ Pointers have high operator precedence, but lower precedence than the
1316
+ dot operator used for field and method access. This can lead to some
1317
+ awkward code filled with parenthesis.
1318
+
1319
+ ~~~
1320
+ # struct Point { x: float, y: float }
1321
+ # enum Shape { Rectangle(Point, Point) }
1322
+ # impl Shape { fn area() -> int { 0 } }
1323
+ let start = @Point { x: 10f, y: 20f };
1324
+ let end = ~ Point { x: (* start).x + 100f, y: (* start).y + 100f };
1325
+ let rect = &Rectangle(* start, * end);
1326
+ let area = (* rect).area();
1327
+ ~~~
1328
+
1329
+ To combat this ugliness the dot operator performs _automatic pointer
1330
+ dereferencing_ on the receiver (the value on the left hand side of the
1331
+ dot), so in most cases dereferencing the receiver is not necessary.
1332
+
1333
+ ~~~
1334
+ # struct Point { x: float, y: float }
1335
+ # enum Shape { Rectangle(Point, Point) }
1336
+ # impl Shape { fn area() -> int { 0 } }
1337
+ let start = @Point { x: 10f, y: 20f };
1338
+ let end = ~ Point { x: start.x + 100f, y: start.y + 100f };
1339
+ let rect = &Rectangle(* start, * end);
1340
+ let area = rect.area();
1341
+ ~~~
1342
+
1343
+ Auto-dereferencing is performed through any number of pointers. If you
1344
+ felt inclined you could write something silly like
1345
+
1346
+ ~~~
1347
+ # struct Point { x: float, y: float }
1348
+ let point = &@~ Point { x: 10f, y: 20f };
1349
+ io::println(fmt!("%f", point.x));
1350
+ ~~~
1351
+
1352
+ The indexing operator (`[]`) is also auto-dereferencing.
1353
+
1287
1354
# Vectors and strings
1288
1355
1289
1356
Vectors are a contiguous section of memory containing zero or more
0 commit comments